JSON对象访问NodeJS TypeError

时间:2016-12-20 18:08:05

标签: javascript json node.js

我在JSON.Parse

之后得到以下对象

undefined

{
  "request": {
    "command": "series",
    "series_id": "PET.RWTC.D"
  },
  "series": [
    {
      "series_id": "PET.RWTC.D",
      "name": "Cushing, OK WTI Spot Price FOB, Daily",
      "units": "Dollars per Barrel",
      "f": "D",
      "unitsshort": "$/bbl",
      "description": "Cushing, OK WTI Spot Price FOB",
      "copyright": "Thomson-Reuters",
      "source": "Thomson-Reuters",
      "iso3166": "USA-OK",
      "geography": "USA-OK",
      "start": "19860102",
      "end": "20161212",
      "updated": "2016-12-14T13:31:06-0500",
      "data": [
        [
          "20161212",
          52.74
        ]
      ]
    }
  ]
}

我正在尝试访问" 52.74"部分使用data.series[0].data[0][1]但得到以下错误

  

TypeError:无法读取属性' 0'未定义的

我错过了什么吗?

更新 - 我正在使用的代码(NodeJS 4.3)

var endpoint = buildEIAURL(event.request.intent.slots.OnDate.value,         event.request.intent.slots.OnDate.value)
        https.get(endpoint, (response) => {
          response.on('data', (chunk) => { body += chunk })
          response.on('end', () => {
            var stringify = JSON.stringify(body)
            var data = JSON.parse(stringify)
            console.log(data.series[0])
            var reqDate = String(new Date(event.request.intent.slots.OnDate.value))
            context.succeed(
              generateResponse(
                buildSpeechletResponse(`The price of oil on ${reqDate} is  $${data.series[0].data[0][1]}`, true),
                {}
              )
            )
          })
        })

1 个答案:

答案 0 :(得分:0)

在我的盒子上工作。请注意,由于多行语法,您需要一个现代的浏览器(或节点)才能运行此代码:

var data = JSON.parse(`{
  "request": {
    "command": "series",
    "series_id": "PET.RWTC.D"
  },
  "series": [
    {
      "series_id": "PET.RWTC.D",
      "name": "Cushing, OK WTI Spot Price FOB, Daily",
      "units": "Dollars per Barrel",
      "f": "D",
      "unitsshort": "$/bbl",
      "description": "Cushing, OK WTI Spot Price FOB",
      "copyright": "Thomson-Reuters",
      "source": "Thomson-Reuters",
      "iso3166": "USA-OK",
      "geography": "USA-OK",
      "start": "19860102",
      "end": "20161212",
      "updated": "2016-12-14T13:31:06-0500",
      "data": [
        [
          "20161212",
          52.74
        ]
      ]
    }
  ]
}`);
console.log(data.series[0].data[0][1])