【问题标题】:Unable to extract json response无法提取 json 响应
【发布时间】:2020-08-18 00:43:20
【问题描述】:

我正在尝试提取 JSON 响应。当我尝试访问 json 数组中的对象时,它返回 undefined

  weather=  [{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}]
 var x=JSON.stringify(weather)
 x[0].main= returns =>undefined

【问题讨论】:

  • 你已经用一个对象字符串化了一个数组;应该是什么问题?这里没有与代码匹配的问题陈述。
  • 你期望的输出是什么?我目前没有看到您的代码有问题!
  • 我只想检索天气中的数据字段,但它总是返回未定义
  • 这是一个字符串。你有一个对象,你把它变成了一个字符串。 weather[0].main

标签: json reactjs axios


【解决方案1】:

您可以简单地使用 Array#mapArray#forEach 函数来获取所有 JSON 数据。您确实不需要在回复中使用JSON.stringify

演示:

let weather = [{
  "id": 711,
  "main": "Smoke",
  "description": "smoke",
  "icon": "50d"
}]

weather.map(function(x) {
  console.log(x.id) //711
  console.log(x.main) //Smoke
  console.log(x.description) //smoke
  console.log(x.icon) //50d
})

【讨论】:

    【解决方案2】:

    我不确定您要完成什么或尝试过什么,但这是它的工作原理:

    const weather = [{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}]
    document.querySelector('#id').textContent = weather[0].id
    document.querySelector('#json').textContent = JSON.stringify(weather)
    ID:
    <div id="id"></div>
    Stringified JSON:
    <div id="json"></div>

    要访问数组的元素,您可以引用索引或循环遍历它:

    const myArray = [1, 2, 3];
    myArray[0] // 1
    myArray[1] // 2
    myArray[2] // 3
    
    for (let i = 0 ; i < myArray.length ; i++) {
        console.log(myArray[i]);
    }
    

    要访问对象的属性,您可以使用点表示法或键名作为索引:

    const myObject = {'a': 1, 'b': 2}
    myObject.a // 1
    myObject['b'] // 2
    

    JSON.stringify 将您的 JSON 转换为字符串。这对于通过连接发送到可能识别或不识别 JSON 的主机很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 2015-05-03
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多