1

I need to parse a json object like {"key1":"val1","key2":"val2","key3":"val3"} in a loop.

Trying:

var inobj = '[{"key1":"val1","key2":"val2","key3":"val3"}]';
var obj = eval(inobj);
    for (var i = 0; i < 3; i++) {
        var key = i;
        var val = obj[key];
        alert (key+' = '+val);
    }

But i don't know hot to know obj.length.

1

2 Answers 2

5
var obj = JSON.parse('{"key1":"val1","key2":"val2","key3":"val3"}');

Object.keys(obj).forEach(function (key) {
    alert(key + " = " + obj[key]);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Or simply for (var key in obj) {...}.
@FelixKling I prefer the Object.keys(obj).forEach(function (key) { .. }) approach since it creates a new scope, avoiding the hoisting issues inherent in for loops.
If a new scope is required then yes, it's a nice approach... otherwise, a simple for seems to have less overhead.
Yeah, I mean, in this example a new scope is not necessarily required, but I can just imagine this user's next question being "why when I call setTimeout inside my for loop does it not work like I expect..." :)
1

You can count poperties:

Object.keys(obj).length

see stack question: How to efficiently count the number of keys/properties of an object in JavaScript?

Comments

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.