我有带引用的 JSON 架构。我必须发出一个 http 请求来获取带有引用的 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 架构作为 request。(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 文件?
基本上我应该将 URL 替换为 'http://www.jsonschema.com/src/JSON_schemas/json_1.json'
为 'http://www.jsonschema.com/src/V1/alternate_ids.json'
以便它进行正确的调用。
但是我将如何以编程方式实现对 URL 的这种操作?
基本上 ref 是远程计算机中文件系统的路径。所以我有基本 URL,当我看到 ref 时,我应该更改我的 URl 以获取该引用的文件
最佳答案
你可以试试下面的代码:
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['属性']
。
split()
将字符串拆分(划分)为子字符串数组。
pop()
删除数组的最后一个元素,并返回该元素。
关于javascript - 获取 URL 并使用 JSON 模式引用对其进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45085219/