javscript-无法解析json对象

时间:2018-10-31 10:51:59

标签: javascript json

我在解析JSON对象时遇到问题,

这是我的代码

var k = '[{"image:loc":["https://cdn.shopify.com/s/files/1/0094/2252/products/YZY-KW3027.053.jpg?v=1539344090"],"image:title":["Yeezy WMNS Tubular Boot Washed Canvas - Limestone"]}]'
var kP = JSON.parse(k);

console.log(kP);

但是当我尝试解析“ image:loc”或“ image:title”时,像这样:console.log(kP['image:loc']); 它返回未定义。

2 个答案:

答案 0 :(得分:0)

由于kP是一个数组,因此要访问任何属性,必须使用适当的 index

var k = '[{"image:loc":["https://cdn.shopify.com/s/files/1/0094/2252/products/YZY-KW3027.053.jpg?v=1539344090"],"image:title":["Yeezy WMNS Tubular Boot Washed Canvas - Limestone"]}]'
var kP = JSON.parse(k);

console.log(kP);
console.log(kP[0]['image:loc']);

答案 1 :(得分:0)

console.log(kP['image:loc']);不起作用,因为kP是一个数组。您需要定位数组的第一个索引以定位对象,如下所示:

var k = '[{"image:loc":["https://cdn.shopify.com/s/files/1/0094/2252/products/YZY-KW3027.053.jpg?v=1539344090"],"image:title":["Yeezy WMNS Tubular Boot Washed Canvas - Limestone"]}]'
var kP = JSON.parse(k);

console.log(kP[0]['image:loc']);