使用Node.js访问嵌套键

时间:2018-09-17 12:26:18

标签: javascript json node.js

我有一个要求,我想列出一个键并使用nodejs返回。

这是我的json结构:

{
        type: "qwqw",
        org: "asdasd",
        pop: "asaswe",
        results: {
            "resultId1": {
                "type": "normal"
                .............
                ..............
             },
             "resultId2": {
                "type": "normal"
                .............
                ..............
             },
             "resultId3": {
                "type": "normal"
                .............
                ..............
             }
       }

因此,这里的预期结果是;像这样的["resultId1", "resultId2", "resultId3"]

这是我尝试过的:

 var keys = Object.keys(jsonString.results);
    for (var i = 0; i < keys.length; i++) {
        console.log(data[keys[i]]);
    }

有人可以使用任何nodejs库帮助我进行json解析吗?

3 个答案:

答案 0 :(得分:2)

您应该尝试一下,因为在javascript中获取密钥非常简单。

var data =  {
                type: "qwqw",
                org: "asdasd",
                pop: "asaswe",
                results: {
                    "resultId1": {
                        "type": "normal"
                     },
                     "resultId2": {
                        "type": "normal"
                     },
                     "resultId3": {
                        "type": "normal"
                     }
                }
           };
           
var output = Object.keys(data.results);
console.log(output);

答案 1 :(得分:0)

data.json文件:     {       “ type”:“ qwqw”,       “ org”:“ asdasd”,       “ pop”:“ asaswe”,       “结果”:{         “ resultId1”:{           “ id”:“ 4001”,           “类型”:“正常”         },         “ resultId2”:{           “ id”:“ 5001”,           “ type”:“普通”         },         “ resultId3”:{           “ id”:“ 6001”,           “ type”:“普通”         }       }     }

Node.js Program :
//Program by Atharva Jawalkar
var fs = require("fs");
var dir = __dirname + "/data.json";
fs.readFile(dir, "utf8", function(err, data) {
  if (err) throw err;
  var obj = JSON.parse(data);

  var obj2 = obj.results;

  var keysArray = Object.keys(obj2);
  var len = keysArray.length;
  for (var i = 0; i < len; i++) {
    var key = keysArray[i]; 
    var value = obj2[key]; 
    console.log(key, value);
  }
});

Output:
resultId1
json_parsing_try3.js:15
Object {id: "4001", type: "normal"}
json_parsing_try3.js:15
resultId2
json_parsing_try3.js:15
Object {id: "5001", type: "Normal"}
json_parsing_try3.js:15
resultId3
json_parsing_try3.js:15
Object {id: "6001", type: "Normal"}

Here i have created data.json file and read that file in program but you can declare your json data in variable also.

答案 2 :(得分:0)

您的代码有误:

var keys = Object.keys(jsonString.results);
for (var i = 0; i < keys.length; i++) {
    console.log(data[keys[i]]);
}

应该是

var keys = Object.keys(jsonString.results);
for (var i = 0; i < keys.length; i++) {
    console.log(keys[i]);
}

请注意console.log参数中第3行的区别。