在JavaScript中读取具有多个对象的JSON响应

时间:2018-12-03 19:36:04

标签: javascript arrays json

我有一个如下的JSON响应。

{
   returnCode: 'Success',
   info: null,
   result: {
       payload: '{
            "BatchNo":"143123",
            "Supplier":"Automotive",
            "ItemNumber":"AP123",
            "ProdNumber":"\\"\\"",
            "ItemIdentifier":"PROCURE"}             
            {
            "BatchNo":"143123",
            "Supplier":"Manufacturing",
            "ItemNumber":"API124",
            "ProdNumber":"PRD123",
            "ItemIdentifier":"PRODUCE"}',
 encode: 'UTF-8'
 },
  txid:'8d9efd6083e6ca737e9c751baecd0c75cf738e9ce0e599bcfa26910575fa6d5f8d9efd6083e'
}

请注意,JSON数据中没有数组[{}]。有人可以帮助我如何访问result.payload.ItemNumber值并获得类似

的输出
AP123
AP124

我尝试下面的代码,但是徒劳。有人请帮助我

 var output1 = JSON.parse(json).result.payload[1].ItemNumber;
 console.log("Data:"+ output1);

谢谢。

1 个答案:

答案 0 :(得分:0)

注意

必须清理有效负载并将其转换为数组,并用逗号分隔对象列表。否则,它是无效的响应数据。

代码

let json = {
   returnCode: 'Success',
   info: null,
   result: {
       payload: '[{"BatchNo":"143123","Supplier":"Automotive","ItemNumber":"AP123","ProdNumber":"\\"\\"","ItemIdentifier":"PROCURE"},{"BatchNo":"143123","Supplier":"Manufacturing","ItemNumber":"API124","ProdNumber":"PRD123","ItemIdentifier":"PRODUCE"}]',
        encode: 'UTF-8'
 },
  txid:'8d9efd6083e6ca737e9c751baecd0c75cf738e9ce0e599bcfa26910575fa6d5f8d9efd6083e'
}

 var output1 = JSON.parse(json.result.payload)[1].ItemNumber;
 console.log("Data:"+ output1);