3

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.

3
  • Why do you need to iterate through the object manually? Isn't the object you want simply JSON.parse(reqTemplate)? 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. Commented Dec 27, 2012 at 12:43
  • Ah, I see. Bergi's answer's the one then :P Commented Dec 27, 2012 at 12:55

3 Answers 3

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) );
Sign up to request clarification or add additional context in comments.

1 Comment

:Thanks i tried your solution and was able to come up with the required output.
2

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.

Comments

0

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.

3 Comments

yup when i tried dat i am able to get oly the parent key say AuthenticateUserReq from the above json.But i also want to get the DeviceInfo (ie)The main keys inside a parent key is not retrived in the above method
But what's your purpose? Why do you want to traverse the JSON? Looking for something? Or you just want to print it out?
I want to traverse the JSON store its keys in a db and also i should be able to bring back the json in its original formal by retrieving its contents from the db

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.