简体   繁体   中英

JSON Object Access NodeJS TypeError

I get the following object after 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
        ]
      ]
    }
  ]
}

I am trying to access the "52.74" portion using data.series[0].data[0][1] but get the following error

TypeError: Cannot read property '0' of undefined

Am I missing something?

Update - Code I am using (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),
                {}
              )
            )
          })
        })

Works on my box. Note you'll need a modern browser (or node) to be able to run this code, due to the multiline syntax:

 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]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM