-1

I'm trying to read the following json file into node js :

myData.json

[
  {"1000000": {
    "name": "ALEX",
    "intern": false,
    "purchase": 76
  }},
  {"2000000": {
    "name": "KELVIN",
    "purchase": false,
    "days": 46
  }},
  {"3000000": {
    "name": "PUTIN",
    "intern": false,
    "purchase": 9
  }}
]
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('./flatSearch.json', 'utf8'));
console.log("Name is " + obj[0]);

Output:

{ '1000000' : { "name": "ALEX",  "intern": false,  "purchase": 76  }}

What I need is : 1) I need just the name or the intern value or purchase value
2) I need just the value 1000000

Could someone help me on how can I fetch these values in node JS ?

  • I think this is already addressed. You may want to look at [here](http://stackoverflow.com/questions/5726729/how-to-parse-json-using-node-js) – Kimia Salmani Jun 21 '16 at 03:10
  • did you try `obj["1000000"]` this – uzaif Jun 21 '16 at 03:15
  • 1
    Your JSON seems to be overly nested. The outer structure should be an object with `1000000`, `2000000`, and `3000000` as keys. Right now you have to iterate the object until you find the right id, when instead you could do a quick property lookup. – 4castle Jun 21 '16 at 03:19
  • In your JSON, is there a guarantee that `1000000` will be at `obj[0]`? If so, do `obj[0]["1000000"]` – 4castle Jun 21 '16 at 03:21

1 Answers1

0

1-a If you need name value: obj[0]['1000000'].name or obj[0]['1000000']['name']

1-b If you need purchase value: obj[0]['1000000'].purchase or obj[0]['1000000']['purchase']

2- If you just need the '1000000' value: obj[0]['1000000']

But in those cases, you need to be sure that the object you want to retrieve has for key name '1000000' and have name and purchase as properties.

You can clearly improve your JSON file.

A lighter JSON example of it:

{
  "1000000": {
    "name": "ALEX",
    "intern": false,
    "purchase": 76
  },
  "2000000": {
    "name": "KELVIN",
    "purchase": false,
    "days": 46
  },
  "3000000": {
    "name": "PUTIN",
    "intern": false,
    "purchase": 9
  }
}
gillyb
  • 8,760
  • 8
  • 53
  • 80
A.I.S
  • 113
  • 3
  • 10