如何将json文件夹加载到Javascript中?

时间:2019-07-02 11:45:58

标签: node.js json angular jsonschema

我想加载(需要)一个具有基于其文件引用的json模式的文件夹。

换句话说,我有

Schema1: 
{ //Schema stuff ....
    "$ref": "./json_schema2_file.json#someElement"
}

在同一文件夹中的另一个文件中:

Schema2
{//Schema stuff...
"$id": "/someElement"
}

这些模式位于单独的文件中,现在应该加载到JS中以针对json对象进行验证。 但是,文件夹内的引用仍应有效。

这就是为什么我的问题是,是否以及如何加载一个充满json文件而没有中断引用的文件夹。

该模式将使用这些模式来验证json对象:https://github.com/tdegrunt/jsonschema 我个人使用的是带有Angular的Node,因此使用fs仅适用于node,但这只是一个开始。

3 个答案:

答案 0 :(得分:1)

在您的Node后端中,require可用于导入JSON文件,就像它是普通的JavaScript文件一样:

// data.json
{ "hello": "world" }

// main.js
const data = require('./data.json');
console.log(data); // { hello: 'world' }

对于Angular前端,这取决于构建包的方式,但是通常使用import data from './data.json'应该会产生相同的结果(如this question中所述)。


现在出现了一个问题:如果您的架构位于多个JSON文件中,该怎么办?

自然,requireimport都不花时间来解析$ref$id属性,并将所有内容捆绑到一个JS对象中。似乎没有任何简单的本机方法可以解析所有内容,幸运的是,NPM软件包json-schema-ref-parser做到了这一点!可以在您的用例中使用它:

// foo.schema.json 
{
    "type": "object",
    "properties": {
        "bar": {
            "$ref": "./bar.schema.json"
        }
    }
}

// bar.schema.json 
{
    "type": "number"
}

// main.js 
const parser = require('json-schema-ref-parser');
parser.dereference('foo.schema.json', (err, schema) => console.log(schema));
// logs: { type: 'object', properties: { bar: { type: 'number' } } }

答案 1 :(得分:0)

通常,JSON Schema解析器(包括我维护的jsonschema包)不会自动重新加载引用。您只需要提供具有以下架构的其他文件即可:

var Validator = require('jsonschema').Validator;
var v = new Validator();
v.addSchema(require('./json_schema.json'), 'http://example.com/json_schema.json');
v.addSchema(require('./json_schema2.json'), 'http://example.com/json_schema2.json');

请不要忘记为您的模式提供完整的URI,否则它们在应用程序之间可能无法保持一致。

如果要自动导入引用,则jsonschema包提供Validator#unresolvedRefs属性中没有定义的已知模式的列表。移开该堆栈,并使用Validator#addSchema导入引用:

async function importUnresolved(){
    for(var uri; uri = v.unresolvedRefs.shift();){
        // where `get` is some resolver that downloads the schema
        schema = await get(uri);
        if(!schema) throw new Error(`Could not dereference JSON schema: <${uri}>`);
        v.addSchema(schema, uri);
    }
}

答案 2 :(得分:-1)

1。使用json解析器编写json内容以避免错别字。

 {
     "quiz": 
     [
         {
             "question": "Question 1",
             "a": "Answer a",
             "b": "Answer b",
             "c": "Answer c",
             "correct": "a"
         },
         {
             "question": "Question 2",
             "a": "Answer a",
             "b": "Answer b",
             "c": "Answer c",
             "correct": "b"
         },
         {
             "question": "Question 3",
             "a": "Answer a",
             "b": "Answer b",
             "c": "Answer c",
             "correct": "c"
         }
     ]
 }

2。将json与js脚本保存在同一文件夹中。我将文件命名为questions.json。 3,用$ .getJSON加载json数据下面的示例是完整的脚本,该脚本将json中的问题加载到allQuestions数组中。

var allQuestions = new Array();
    
function loadQuestions() {
    $.getJSON('question.json', function (data) {
        allQuestions = data.quiz;
    }).error(function(){
            console.log('error: json not loaded');
        });
    });
}

4。现在,您的json数据在allQuestions数组中可用,您可以访问它,例如:

var currentQuestion = allQuestions[0].question;
var answerA         = allQuestions[0].a; 

使用.done回调 请记住,$ getJSON是异步运行的。这样的实现不是最好的主意:

loadQuestions();
printQuestion(allQuestions[0]); 

有可能在调用printQuestion时尚未加载JSON,而allQuestions的大小将为0。为确保在完全加载JSON之后执行某些操作,请使用.done回调。

var allQuestions = new Array();
    
function loadQuestions() {
    $.getJSON('question.json', function (data) {
        allQuestions = data.quiz;
    })
    .error(function() {
        console.log('error: JSON not loaded'); 
    })
    .done(function() {
        console.log( "JSON loaded!" );
        printQuestion(allQuestions[0]); 
    });
}