迭代嵌套的JSON数组

时间:2019-06-18 13:12:11

标签: javascript json

我的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")

2 个答案:

答案 0 :(得分:1)

解析Json字符串的方法有很多,但是这里有一个纯js函数可以为您做到这一点:

JSON.parse(JsonString)

答案 1 :(得分:0)

您可以这样访问它

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)
});