BenTen
BenTen

Reputation: 403

How to read JSON response data with a space in path in JavaScript

I am trying to read JSON response data from a Restful API that contains a space in the path. I am trying to accomplish this in JavaScript, but can't seem to get the data to display.

Below is the JSON I am working with:

"fields": {
  "census": {...},
  "acs": {
    "meta": {
      "source": "American Community Survey from the US Census Bureau",
      "survey_years": "2014-2018",
      "survey_duration_years": "5"
    },
    "demographics": {
      "Median age": {
        "meta": {
          "table_id": "B01002",
          "universe": "Total population"
        },
        "Total": {
          "value": 32.8,
          "margin_of_error": 0.6

As you can see, the Median Age field has a space. The actual data I am trying to obtain is the Median age total value.

Below is my JSON path that isn't working:

        let ageDems = await response.data.results[0].fields.demographics.$["Median age"].Total.value;

I have also tried to use ['Median Age'], ["Median Age"] and Median+Age and none of those worked either. Can anyone please assist me in writing the correct path to obtain the data I need?

Upvotes: 0

Views: 876

Answers (3)

Randy Casburn
Randy Casburn

Reputation: 14175

Ismail's suggestion does work.

This answer is here just to prove it to you. If this is not working for you as demonstrated below, please provide a Minimal, Reproducible Example that shows the error you see.

const data = {
  "acs": {
    "meta": {
      "source": "American Community Survey from the US Census Bureau",
      "survey_years": "2014-2018",
      "survey_duration_years": "5"
    },
    "demographics": {
      "Median age": {
        "meta": {
          "table_id": "B01002",
          "universe": "Total population"
        },
        "Total": {
          "value": 32.8,
          "margin_of_error": 0.6
        }
      }
    }
  }
};

console.log(data.acs.demographics["Median age"].Total.value);

Upvotes: 1

ansonws
ansonws

Reputation: 88

demographics is nested under acs:

await response.data.results[0].fields.acs.demographics["Median age"].Total.value

Upvotes: 0

Ismail
Ismail

Reputation: 131

await response.data.results[0].fields.demographics["Median age"].Total.value;

Upvotes: 2

Related Questions