0

I am trying to parse JSON with JS, there is a array and is not working as intended. I have other API's in my program that i have parced. Here is the data

{
  "cases": {
    "6/5/20": 6774904,
    "6/6/20": 6901877,
    "6/7/20": 7015312,
    "6/8/20": 7119002,
    "6/9/20": 7236054
  },
  "deaths": {
    "6/5/20": 396204,
    "6/6/20": 400051,
    "6/7/20": 402792,
    "6/8/20": 406543,
    "6/9/20": 411436
  },
  "recovered": {
    "6/5/20": 2961441,
    "6/6/20": 3032630,
    "6/7/20": 3087135,
    "6/8/20": 3238065,
    "6/9/20": 3319551
  }
}

The code that I am using for this is here.

    const response = await fetch("https://disease.sh/v2/historical/all?lastdays=5");
    const data = await response.json();
    var casesH = data.cases[0];

    msg.channel.send(casesH);
    console.log(casesH);

Does anyone know what I could be doing wrong or what to do?

Thanks

Craicerjack
  • 6,203
  • 2
  • 31
  • 39
  • youre trying to access your data as if it was an array. Its not, its an object so you have to access it by key. `data.cases["6/5/20"]` – Craicerjack Jun 10 '20 at 23:45
  • 1
    There are no arrays in your question, only objects. Perhaps you want [`Object.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values) if you don't know or care about the keys – Phil Jun 10 '20 at 23:45

2 Answers2

-1

Simple. That isn't an array, it's an object with three properties: cases, deaths, and recovered. Each of those properties is itself an object. To get cases, you instead want to index like so:

const data = await fetch(`url`).then(res => res.json());

const cases = data['cases'];

Alternatively, you should be able to use ES6 destructuring:

const { cases, deaths, recovered } = await fetch(`url`).then(res => res.json());
matthew-e-brown
  • 2,837
  • 1
  • 10
  • 29
-2

JSON is not an array, should be

{
"cases": [
    "6/5/20": 6774904,
    "6/6/20": 6901877,
    "6/7/20": 7015312,
    "6/8/20": 7119002,
    "6/9/20": 7236054
  ],
  "deaths": [
    "6/5/20": 396204,
    "6/6/20": 400051,
    "6/7/20": 402792,
    "6/8/20": 406543,
    "6/9/20": 411436
  ],
  "recovered": [
    "6/5/20": 2961441,
    "6/6/20": 3032630,
    "6/7/20": 3087135,
    "6/8/20": 3238065,
    "6/9/20": 3319551
  ]
}
Craicerjack
  • 6,203
  • 2
  • 31
  • 39
Nonik
  • 645
  • 4
  • 11