简体   繁体   中英

Parsing a json tree in nodejs

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.

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.com/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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