简体   繁体   English

从javascript中的文件读取json

[英]reading json from file in javascript

I have this json file: 我有这个json文件:

test.json : 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? 我究竟做错了什么?

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 ). 其中row是保存属性名称而不是对象的变量,因此您需要使用属性名称来检索它(请参阅: for...in循环文档 )。 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...in迭代器中使用for...in ,简单的for循环就足够了。

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循环

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 use Array#forEach method to iterate. 由于该属性保存一个数组,因此请使用Array#forEach方法进行迭代。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM