0

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?

0

1 Answer 1

3

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);
}


With a simple for loop

for (var i=0;i < json.rows.length; i++) {
  console.log(json.rows[i].key);
}

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

for (var i = 0; i < json.rows.length; i++) {
  console.log(json.rows[i].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);
})

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

4 Comments

why would json variable has a property named row? shoun't the json var which I read have property named rows and each var row has a property named key? (according to json structure test.json)
@PranavCBalan yes I understand that the for loop iterates the properties I don't get why each json variable should even have a property named row! shouldn't json var read represent the json.test it has no property named row
the first for prints nothing and the second way (Object.keys) does yield value and then value

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.