[英]Getting URL and manipulating it with JSON schema references
I have JSON schema with references. 我有带引用的JSON模式。 I have to make a http request to get JSON schema with references.Below is my HTTP request call in Javascript.
我必须发出一个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 {};
I get JSON schema as request like this.(json_1.json as request.responseText) 我像这样的请求得到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."
}
}
}
Now how will I make a call to get "../V1/alternate_ids.json" JSON file? 现在,我将如何调用以获取“ ../V1/alternate_ids.json”JSON文件?
basically I should replace URL to 'http://www.jsonschema.com/src/JSON_schemas/json_1.json'
to 'http://www.jsonschema.com/src/V1/alternate_ids.json'
for it to make a correct call. 基本上,我应该将URL替换为
'http://www.jsonschema.com/src/JSON_schemas/json_1.json'
替换为'http://www.jsonschema.com/src/V1/alternate_ids.json'
,以使其正确的电话。
But how will I achieve this manipulation of URLs programmatically? 但是如何以编程方式实现对URL的这种操纵?
Basically the ref is path to file system in remote computer. 基本上,ref是远程计算机中文件系统的路径。 So I have the base URL and as and when I see ref I should change my URl to get the that referenced file
所以我有了基本URL,当我看到ref时,应该更改我的URl以获取该引用文件
You can try the code below: 您可以尝试以下代码:
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);
Explanation: 说明:
JSON object is basically a JavaScript object and then the data could be accessed inside it using the same dot/bracket notation for the JavaScript objects: jsonSchema['properties']
. JSON对象基本上是一个JavaScript对象,然后可以使用与JavaScript对象相同的点/括号表示法来访问数据:
jsonSchema['properties']
。
split()
splits (divides) a string into an array of substrings. split()
将字符串拆分(划分)为子字符串数组。
pop()
removes the last element of an array, and returns that element. pop()
删除数组的最后一个元素,然后返回该元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.