0

I need to get data from this json but can't figure out the right path

[{
    "type": "qrcode",
    "symbol": [{
        "seq": 0,
        "data": "Hello Test!!!",
        "error": null
    }]
}]

I am trying:

await fetch(QR_URL)
.then(response => response.json())
.then(json => {
console.log(json.symbol.data)
}

and that is giving me error Cannot read property 'data' of undefined

  • 3
    `.symbol` is an array, `[...]`, containing one object, `{...}` - you can access the `data` using `.symbol[0].data` – Mulan May 13 '20 at 00:43
  • Ugh, `json` is not an array Mark, it's an object here. But the name `json` is bad anyway because JSON is always a string! – Mulan May 13 '20 at 00:44
  • @Thankyou Sure looks like array to me – charlietfl May 13 '20 at 00:47
  • And people should stop using low-level `fetch` for everything. Write a reusable function for common tasks, `const fetchJson = (url = "") => fetch(url).then(r => r.json())`, then use it other places in your program, `fetchJson(QR_URL).then(res => res.symbol[0].data)` – Mulan May 13 '20 at 00:47
  • @charlietfl i'm talking about the value of `json` in `.then(json => ...)` – Mulan May 13 '20 at 00:48
  • @Thankyou Right...and the body content shown is wrapped in `[]` – charlietfl May 13 '20 at 00:48

0 Answers0