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.

skywind
  • 892
  • 6
  • 22
  • 44
  • 1
    Related: http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript and http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-access-a-specific-value – Felix Kling Nov 06 '12 at 06:59

2 Answers2

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

Object.keys(obj).forEach(function (key) {
    alert(key + " = " + obj[key]);
});
Domenic
  • 110,262
  • 41
  • 219
  • 271
  • Or simply `for (var key in obj) {...}`. – Felix Kling Nov 06 '12 at 06:58
  • @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. – Domenic Nov 06 '12 at 07:01
  • If a new scope is required then yes, it's a nice approach... otherwise, a simple `for` seems to have less overhead. – Felix Kling Nov 06 '12 at 07:03
  • 1
    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..." :) – Domenic Nov 06 '12 at 07:06
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?

Community
  • 1
  • 1
karaxuna
  • 26,752
  • 13
  • 82
  • 117