我有带有引用的JSON模式。我必须发出一个http请求才能使用references.Below获取JSON,这是我在Javascript中的HTTP调用。
var request = new XMLHttpRequest();
request.open('POST', 'http://www.jsonschema.com/src/JSON_schemas/json_1.json', false);
request.send(null);
if (request.status === 200) {
return JSON.parse(request.responseText);
}
else
return {};
我得到请求这样的JSON模式(json_1.json为request.responseText)。
{
"$schema" : "http://...",
"id" : "67",
"type" : "object",
"properties": {
"accountId": {
"type": "string"
},
"alternateIds": {
"$ref": "../V1/alternate_ids.json"
},
"associations": {
"$ref": "../V1/associations.json"
},
"layers": {
"type": "array",
"$ref": "../V1/account_layers.json"
},
"transactions": {
"$ref": "transactions.json",
"description": "This is an optional field."
}
}
}
现在,我将如何打电话获取"../V1/alternate_ids.json" JSON文件?
基本上,我应该将'http://www.jsonschema.com/src/JSON_schemas/json_1.json'
的URL替换为'http://www.jsonschema.com/src/V1/alternate_ids.json'
,这样才能做出正确的调用。
但是,如何以编程方式实现对URL的操作呢?
从根本上讲,参考文件是远程计算机中文件系统的路径。因此,我有基本的URL,当我看到ref时,我应该更改我的URl以获得那个引用的文件。
发布于 2017-07-13 20:26:59
您可以尝试下面的代码:
var basicUrl = "http://www.jsonschema.com/src"
var jsonSchema = JSON.parse(request.responseText);
var jsonProperties = jsonSchema['properties'];
var alternateIdsRef = jsonProperties['alternateIds']['$ref'];
var truncatedRef = alternateIdsRef.split('..').pop();
var myUrl = basicUrl + truncatedRef;
console.log(myUrl);
解释:
JSON对象基本上是一个JavaScript对象,然后可以使用与JavaScript对象相同的点/括号表示法来访问其中的数据:jsonSchema['properties']
。
split()
将字符串拆分成一个子字符串数组。
pop()
移除数组的最后一个元素,并返回该元素。
https://stackoverflow.com/questions/45085219
复制相似问题