Jas Jas - 5 months ago 15
Javascript Question

reading json from file in javascript

I have this json file:

test.json
:

{"rows" : [
{"key": "value"},
{"key": "value"}
]
}


I tried this code to read it:

var json = require('test.json');
for (var row in json.rows) {
console.log(row.key);
}


it prints:

/usr/local/bin/node json-parser.js
undefined
undefined


What am I doing wrong?

Answer

Where row is the variable holding property name not the object, so you need to retrieve it using the property name ( Refer : for...in loop documentation). In your case it will be the index of array. There is no need to use for...in iterator here, a simple for loop is enough.

for (var row in json.rows) {
  console.log(json.rows[row].key);
}

var json = {
  "rows": [{
    "key": "value"
  }, {
    "key": "value"
  }]
};

for (var row in json.rows) {
  console.log(json.rows[row].key);
}


Since the property holds an array useArray#forEach method to iterate.

json.rows.forEach(function(v){
  console.log(v.key);
}

var json = {
  "rows": [{
    "key": "value"
  }, {
    "key": "value"
  }]
};

json.rows.forEach(function(v) {
  console.log(v.key);
})

Comments