提问人:Baobab 提问时间:3/10/2021 更新时间:3/10/2021 访问量:512
如何根据对象的索引号解析JSON
how to parse json based on index number of object
问:
我有 json 格式的数据,我需要访问数组中每个对象中包含的数据。因此,例如,如果我需要第二个对象(即“202103092000”)中的时间戳,那么我的语法需要是什么才能将第二个对象中的“period”值分配给声明的变量?我尝试过这种方法的变体,但似乎不起作用:
var data4 = JSON.parse(message.payloadString);
fcperiod2 = data4.[1].period;
解析的 json 数据如下所示。我无法控制它的格式,因为它来自 api。
[{
"period": "202103092000",
"condition": "A mix of sun and cloud",
"temperature": "0",
"icon_code": "02",
"precip_probability": "0"
}, {
"period": "202103092100",
"condition": "Mainly sunny",
"temperature": "2",
"icon_code": "01",
"precip_probability": "0"
}, {
"period": "202103092200",
"condition": "Sunny",
"temperature": "2",
"icon_code": "00",
"precip_probability": "0"
}, {
"period": "202103092300",
"condition": "Sunny",
"temperature": "3",
"icon_code": "00",
"precip_probability": "0"
}]
感谢您的任何指示。
猴面包树
答:
1赞
basic
3/10/2021
#1
它仍然是一个数组,因此您不会使用 .[4] 你可以说通过说 data4[X].period 来获取实际数组的 X 元素
顶级域名;替换 data4。[1] 与 data4[1].period
let message = { payloadString: [{
"period": "202103092000",
"condition": "A mix of sun and cloud",
"temperature": "0",
"icon_code": "02",
"precip_probability": "0"
}, {
"period": "202103092100",
"condition": "Mainly sunny",
"temperature": "2",
"icon_code": "01",
"precip_probability": "0"
}, {
"period": "202103092200",
"condition": "Sunny",
"temperature": "2",
"icon_code": "00",
"precip_probability": "0"
}, {
"period": "202103092300",
"condition": "Sunny",
"temperature": "3",
"icon_code": "00",
"precip_probability": "0"
}]
}
var data4 = message.payloadString;
fcperiod2 = data4[1].period;
console.log(fcperiod2)
1赞
Thomas Kay
3/10/2021
#2
在本例中,您有一个包含多个对象的数组。只需使用 .要获取键的值,可以使用 .data4[1]
period
data4[1].period
1赞
mplungjan
3/10/2021
#3
您可以提取所有句点,然后决定您想要哪个句点
const data = [{
"period": "202103092000",
"condition": "A mix of sun and cloud",
"temperature": "0",
"icon_code": "02",
"precip_probability": "0"
}, {
"period": "202103092100",
"condition": "Mainly sunny",
"temperature": "2",
"icon_code": "01",
"precip_probability": "0"
}, {
"period": "202103092200",
"condition": "Sunny",
"temperature": "2",
"icon_code": "00",
"precip_probability": "0"
}, {
"period": "202103092300",
"condition": "Sunny",
"temperature": "3",
"icon_code": "00",
"precip_probability": "0"
}]
const periods = data.map(({period}) => period)
console.log(periods)
console.log(periods[1])
评论