簡體   English   中英

獲取URL並使用JSON模式引用進行操作

[英]Getting URL and manipulating it with JSON schema references

我有帶引用的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模式。(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['properties']

split()將字符串拆分(划分)為子字符串數組。

pop()刪除數組的最后一個元素,然后返回該元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM