最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parsing a json tree in nodejs - Stack Overflow

programmeradmin7浏览0评论

I need to parse a json placed in a file and identify its structure below is the code where I tried doing that

var fs = require('fs')
var reqTemplate;
var obj;
fs.readFile('SampleData.js', 'utf8', function (err, data) {
    if (err) {
        return console.log(err);
    }
    reqTemplate = data;
    console.log('\nRequestTemplate:\n\n%s\n', reqTemplate);
    obj = JSON.parse(reqTemplate);
    var i = 0;
    console.log(Object.keys(obj));
    Object.keys(obj).forEach(function (key) {
        i++;
        console.log;
        console.log(key);
        console.log(obj[key]);
    });
});

The output that I got is:

{
    "AuthenticateUserReq": {
        "Tid": "123",
        "username": "131329",
        "password": "Vinod",
        "SessionTokenId": "",
        "DeviceInfo": {
            "DeviceName": "ABC",
            "DeviceVersion": "X",
            "UniqueDeviceID": "ZZZ",
            "Platform": "AND"
        }
    }
}

I'm able to get the parent key and its values.
I'm stuck as how to identify the child key and retrieval of its values.

PS: I wont be aware of the structure of the json response. I need to identify the root key and its value and also the children key and their values.

Any help will be much appreciated.

I need to parse a json placed in a file and identify its structure below is the code where I tried doing that

var fs = require('fs')
var reqTemplate;
var obj;
fs.readFile('SampleData.js', 'utf8', function (err, data) {
    if (err) {
        return console.log(err);
    }
    reqTemplate = data;
    console.log('\nRequestTemplate:\n\n%s\n', reqTemplate);
    obj = JSON.parse(reqTemplate);
    var i = 0;
    console.log(Object.keys(obj));
    Object.keys(obj).forEach(function (key) {
        i++;
        console.log;
        console.log(key);
        console.log(obj[key]);
    });
});

The output that I got is:

{
    "AuthenticateUserReq": {
        "Tid": "123",
        "username": "131329",
        "password": "Vinod",
        "SessionTokenId": "",
        "DeviceInfo": {
            "DeviceName": "ABC",
            "DeviceVersion": "X",
            "UniqueDeviceID": "ZZZ",
            "Platform": "AND"
        }
    }
}

I'm able to get the parent key and its values.
I'm stuck as how to identify the child key and retrieval of its values.

PS: I wont be aware of the structure of the json response. I need to identify the root key and its value and also the children key and their values.

Any help will be much appreciated.

Share Improve this question edited Dec 27, 2012 at 11:02 Cerbrus 73k19 gold badges136 silver badges150 bronze badges asked Dec 27, 2012 at 10:54 Amanda GAmanda G 1,99111 gold badges33 silver badges44 bronze badges 3
  • Why do you need to iterate through the object manually? Isn't the object you want simply JSON.parse(reqTemplate)? – Cerbrus Commented Dec 27, 2012 at 11:43
  • @Cerbrus:That is just giving me the entire response.I want to get the individual keys and their values. – Amanda G Commented Dec 27, 2012 at 12:43
  • Ah, I see. Bergi's answer's the one then :P – Cerbrus Commented Dec 27, 2012 at 12:55
Add a ment  | 

3 Answers 3

Reset to default 4

You will need recursion for tree traversal:

var callback = console.log;

function traverse(obj) {
    if (obj instanceof Array) {
        for (var i=0; i<obj.length; i++) {
            if (typeof obj[i] == "object" && obj[i]) {
                callback(i);
                traverse(obj[i]);
            } else {
                callback(i, obj[i])
            }
        }
    } else {
        for (var prop in obj) {
            if (typeof obj[prop] == "object" && obj[prop]) {
                callback(prop);
                traverse(obj[prop]);
            } else {
                callback(prop, obj[prop]);
            }
        }
    }
}

traverse( JSON.parse(reqTemplate) );

Might also want to try out Node traverse - https://github./substack/js-traverse. Allows recursively walking a JSON tree to get each key value pair with context (ie: keeps track of parent), and can run map/reduce while traversing tree. Very powerful.

When you parse a JSON you get a normal JS object. You can obtain its keys by using var keysOfObject = Object.keys(object);. Then you can use those keys to get the values.

发布评论

评论列表(0)

  1. 暂无评论