簡體   English   中英

迭代嵌套的JSON數組

[英]Iterate a nested JSON array

我的JSON如下:

{
   "ok":false,
   "status":400,
   "statusText":"Bad Request",
   "body":{
      "message":"An error occurred while trying to update the record. Please try again.",
      "statusCode":400,
      "enhancedErrorType":"RecordError",
      "output":{
         "errors":[

         ],
         "fieldErrors":{
            "Product_L2__c":[
               {
                  "constituentField":null,
                  "duplicateRecordError":null,
                  "errorCode":"FIELD_CUSTOM_VALIDATION_EXCEPTION",
                  "field":"Product_L2__c",
                  "fieldLabel":"Product L2",
                  "message":"Product L2 is required"
               }
            ]
         }
      }
   }
}

我想從此JSON獲取errorCode(FIELD_CUSTOM_VALIDATION_EXCEPTION)message("Product L2 is required")

解析Json字符串的方法有很多,但是這里有一個純js函數可以為您做到這一點:

JSON.parse(JsonString)

您可以像這樣訪問

var jsondata = {
  "ok": false,
  "status": 400,
  "statusText": "Bad Request",
  "body": {
    "message": "An error occurred while trying to update the record. Please try again.",
    "statusCode": 400,
    "enhancedErrorType": "RecordError",
  "output": {
    "errors": [],
    "fieldErrors": {
      "Product_L2__c": [{
        "constituentField": null,
        "duplicateRecordError": null,
        "errorCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION",
        "field": "Product_L2__c",
        "fieldLabel": "Product L2",
        "message": "Product L2 is required"
      }]
    }
   }
  }
 }

var innerKey = Object.keys(jsondata.body.output.fieldErrors)[0];
jsondata.body.output.fieldErrors[innerKey].forEach(
function(record){
   console.log(record.errorCode+" "+record.message)
});

暫無
暫無

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

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