简体   繁体   中英

Getting URL and manipulating it with JSON schema references

I have JSON schema with references. I have to make a http request to get JSON schema with references.Below is my HTTP request call in Javascript.

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)

{
  "$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?

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.

But how will I achieve this manipulation of URLs programmatically?

Basically the ref is path to file system in remote computer. So I have the base URL and as and when I see ref I should change my URl to get the that referenced file

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'] .

split() splits (divides) a string into an array of substrings.

pop() removes the last element of an array, and returns that element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM