1

I know there are several threads on this subject but I've looked through over 30 threads without success. I have managed to parse a JSON response so it looks like this:

   {
    "1": {
       "id": "1",
       "name": "Fruit",
       .
       .
       .
       "entities": {
          "1": {
            "id": "1",
            "name": "blue bird",
       .
       .
       .
       "status": "1"
    },
   "2": {

using this code

    let json = JSON.parse(body);
    console.log(json); 

Now I want to access the "id", "name" etc. AND the "id" and "name" for the "entities" tag. So far I have tried:

    console.log(json[0]);
    console.log(json.id);

which both returns undefined

I have also tried

    console.log(json[0].id);

which gives an error

Any ideas?

3
  • 2
    looks like your first key is json["1"] Commented Nov 14, 2019 at 0:27
  • LOL easy fix haha thanks! Commented Nov 14, 2019 at 0:29
  • Sure, I'll add as an answer Commented Nov 14, 2019 at 0:34

3 Answers 3

2

In this instance, your first key is 1, so you can access it with json[1].

const json = {
  "1": {
    "id": "1",  
    "name": "Fruit"
  },
  "2": {
    "id": "2",  
    "name": "Veggies"
  }
};

console.log(json[1]);

Sign up to request clarification or add additional context in comments.

Comments

0

In this json, you can reach the id by

json.1.id

But I think that first of all your json is not correctly written, you should have something like

{ 
"elements": [
    { "id" : 1, "name" : "fruit" },
    { "id" : 2, "name" : "vegetable" }
]
}

like that, json.elements is a collection/array, and you can loop, count, or any other things you will not be able to do because your json looks like a super heavy list of different properties ( he doesn't know that json.1 and json.2 are the same type of objects.

Comments

0
const jsonData = JSON.parse(body);

for (const i in jsonData) {
  for (const j in jsonData[i]) {
    console.log('${i}: ${jsonData[i][j]}');
  }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.