如何在JavaScript

时间:2016-10-28 15:13:12

标签: javascript json

我试图浏览一个复杂的嵌套JSON,但是我的尝试并没有让我走得太远,因为它一直让我回到最后index JSON。

这就是我的对象的样子,并尝试浏览它并获取$ref中的其他objs /模式。

enter image description here

Raw JSON

 {
   "type": "object",
   "properties": {
      "Id": {
         "format": "int32",
         "type": "integer"
      },
      "Status": {
         "enum": [
            "Preparing",
            "AwaitingCompletion",
            "Cancelled",
            "Completed"
         ],
         "type": "string"
      },
      "ExternalReference": {
         "type": "string"
      },
      "Customer": {
         "$ref": "#/definitions/Customer"
      },
      "OrderLineGroups": {
         "type": "array",
         "items": {
            "$ref": "#/definitions/OrderLineGroup"
         }
      },
      "Promotions": {
         "type": "array",
         "items": {
            "$ref": "#/definitions/PromotionSummary"
         }
      },
      "OriginatingSite": {
         "type": "object",
         "properties": {
            "Id": {
               "format": "int32",
               "type": "integer"
            },
            "PropertyCode": {
               "type": "string"
            },
            "StoreCode": {
               "type": "string"
            }
         }
      },
      "CustomData": {
         "type": "object",
         "additionalProperties": {
            "type": "array",
            "items": {
               "type": "object"
            }
         }
      }
   }
}

在我的代码中,我完成了for()hasOwnProperty(),但我的问题是即使符合条件,它也不会给我所有的JSON(例如,如果有的话)没有类型属性),它只给出最后index或没有type属性的对象。如果type属性为array,也不会向我返回任何对象。

// Get property of #/definitions/obj
let prop =  apiDefinition[splitResponse.split('/')[2]].properties;
console.log([prop])
var s = [apiDefinition[splitResponse.split('/')[2]].properties];

// Transform JS Object of #/definitions/Obj to JSON 
var parentJSON = JSON.stringify(apiDefinition[splitResponse.split('/')[2]]);

for (var x in prop) {
  if (prop.hasOwnProperty(x)) {
    if (prop[x].type && prop[x].type === 'array') {
      console.log('All type Array >> ', x);
      let objKeyProp = apiDefinition[prop[x].items.$ref.split('/')[2]];
      let objJsonStringified = JSON.stringify(objKeyProp);
      let refString = '{"$ref"'+':' + '"' + prop[x].items.$ref + '"}';
      this.compiledJson = JSON.parse(parentJSON.replace(refString, objJsonStringified)); 
    } else if (!prop[x].type) {
      console.log('all arrays >> ', x)
      let objKeyProp = apiDefinition[prop[x].$ref.split('/')[2]];
      let objJsonStringified = JSON.stringify(objKeyProp);
      let refString = '{"$ref"'+':' + '"' + prop[x].$ref + '"}';
      this.compiledJson = JSON.parse(parentJSON.replace(refString, objJsonStringified));
    }
  }
}

0 个答案:

没有答案