-2

I have tried to parse this JSON file. But I see undefined. I need to receive only value, where the key equals level1.

[{
  "id": 2,
  "name": "Peter",
  "products": [{
      "title": "first",
      "price": 100
    },
    {
      "title": "second",
      "price": 200,
      "desciption": [{
          "level1": "good",
          "level2": "bad"
        },

        {
          "level3": "super",
          "level4": "hell"
        }

      ]
    }

  ],
  "country": "USA"
}]

const fs = require('fs');
let file = fs.readFileSync("./file.json");

let parsed = JSON.parse(file);

console.log(parsed["name"])
console.log(parsed.name);

and I see in the conlose "undefined"

adiga
  • 34,372
  • 9
  • 61
  • 83
Pavlo NN
  • 75
  • 1
  • 6

1 Answers1

0

Your JSON data represents an array of objects. If after parsing you want the property "name" of the first element, it's:

console.log(parsed[0]["name"])

or

console.log(parsed[0].name);
Aioros
  • 4,373
  • 1
  • 18
  • 21
  • Thank you! But If I tried console.log(parsed['products'[1]['title']]); I see undefined or console.log(parsed.products[0].title); it doesn`t work Please, help with it – Pavlo NN Jul 01 '19 at 18:43
  • `parsed['products'[1]['title']]` does not mean much and is not even valid JS. If you mean "the `title` property of the second element of `parsed`", it's parsed[1]['title']. – Aioros Jul 01 '19 at 20:07