Javascript React Native:访问JSON
目前我想使用我获取的JSON数据。我的数据如下所示:Javascript React Native:访问JSON,javascript,react-native,Javascript,React Native,目前我想使用我获取的JSON数据。我的数据如下所示: { "0": { "date": "2018-12-06T20:49:02.489000", "encoded": "B64Encoded", "height": "390", "name": "image2.jpg", "width": "390" }, "1": { "date": "2018-12-06T20:49:02.489000", "encoded": "B64Encod
{
"0": {
"date": "2018-12-06T20:49:02.489000",
"encoded": "B64Encoded",
"height": "390",
"name": "image2.jpg",
"width": "390"
},
"1": {
"date": "2018-12-06T20:49:02.489000",
"encoded": "B64Encoded",
"height": "136",
"name": "index.jpg",
"width": "371"
}
}
我的问题在于访问JSON数据。一直以来,当我尝试
fetch('http://127.0.0.1:8888')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
jsonData: responseJson[0].name
})
});
我最终得到了一个未定义的对象。我认为问题在于如何定义JSON。如何正确访问它
fetch('http://127.0.0.1:8888')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
jsonData: responseJson['0'].name
})
});
请注意0responseJson.0.name周围的引号“0”,因为0是对象的键。您也可以使用responseJson[“0”]。name@Milore:这是无效的语法。可以使用括号或点符号访问任何属性。在此了解更多信息:您访问对象的方式似乎很好。我们需要更多的信息。什么是
console.log(typeof responseJson)
和console.log(responseJson)
输出?还请注意,您没有访问JSON(严格来说)。您正在访问通过解析JSON生成的JavaScript值。请自己尝试:console.log({0':42}[0])
您编写的语法永远无效。尝试constobj={'0':42};obj['0']
我的意见是,无论您使用的是[0]
还是['0']
,都无关紧要。这是相同的,因此它无法解决OP的问题。“您编写的语法永远无效。”您是否确实尝试过在浏览器的控制台中运行console.log({'0':42}[0])
?它可以工作:没有语法错误,并且打印42
。因此,是的,它是有效的。不知道我还能怎么说服你。