如何在多维响应中读取json数据

时间:2016-12-22 05:37:06

标签: json node.js

如何解析节点中的以下数据我想按键读取值,如special_price = 10.0000&成本= 20.0000

   [  
   {  
      "attributeCode":"description",
      "value":"<p>The sporty Joust Duffle Bag can't be beat - not in the gym, not on the luggage carousel, not anywhere. Big enough to haul a basketball or soccer ball and some sneakers with plenty of room to spare, it's ideal for athletes with places to go.</p>\r\n<ul>\r\n<li>Dual top handles.</li>\r\n<li>Adjustable shoulder strap.</li>\r\n<li>Full-length zipper.</li>\r\n<li>L 29\" x W 13\" x H 11\".</li>\r\n</ul>"
   },
   {  
      "attributeCode":"special_price",
      "value":"10.0000"
   },
   {  
      "attributeCode":"special_from_date",
      "value":"2016-12-20 00:00:00"
   },
   {  
      "attributeCode":"cost",
      "value":"20.0000"
   },
]

2 个答案:

答案 0 :(得分:1)

如果要解析对象

var responseArr = [  
   {  
      "attributeCode":"description",
      "value":"<p>The sporty Joust Duffle Bag can't be beat - not in the gym, not on the luggage carousel, not anywhere. Big enough to haul a basketball or soccer ball and some sneakers with plenty of room to spare, it's ideal for athletes with places to go.</p>\r\n<ul>\r\n<li>Dual top handles.</li>\r\n<li>Adjustable shoulder strap.</li>\r\n<li>Full-length zipper.</li>\r\n<li>L 29\" x W 13\" x H 11\".</li>\r\n</ul>"
   },
   {  
      "attributeCode":"special_price",
      "value":"10.0000"
   },
   {  
      "attributeCode":"special_from_date",
      "value":"2016-12-20 00:00:00"
   },
   {  
      "attributeCode":"cost",
      "value":"20.0000"
   },
]

var responseObj = responseArr.reduce(function(obj, elm){
  obj[elm.attributeCode] = elm.value;
  return obj;
}, {})

console.log(responseObj) // Object {description: "<p>The sporty Joust Duffle Bag can't be beat - not…per.</li><li>L 29" x W 13" x H 11".</li></ul>", special_price: "10.0000", special_from_date: "2016-12-20 00:00:00", cost: "20.0000"}

然后您可以responseObj.special_priceresponseObj.cost。 并且别忘了parseFloat。

答案 1 :(得分:0)

希望它对你有所帮助。

function parse(data, attribute){
    for(var index in data){
       if(data[index]["attributeCode"] == attribute)
          return data[index]["value"];
    }
    return null;
}

e.g。

var body=[  
  {  
     "attributeCode":"description",
     "value":"<p>The sporty Joust Duffle Bag can't be beat - not in the gym, not on the luggage carousel, not anywhere. Big enough to haul a basketball or soccer ball and some sneakers with plenty of room to spare, it's ideal for athletes with places to go.</p>\r\n<ul>\r\n<li>Dual top handles.</li>\r\n<li>Adjustable shoulder strap.</li>\r\n<li>Full-length zipper.</li>\r\n<li>L 29\" x W 13\" x H 11\".</li>\r\n</ul>"
  },
  {  
     "attributeCode":"special_price",
     "value":"10.0000"
  },
  {  
     "attributeCode":"special_from_date",
     "value":"2016-12-20 00:00:00"
  },
  {  
     "attributeCode":"cost",
     "value":"20.0000"
  },
];

console.log(parse(body, "special_price"));  //10.000