media
media

Reputation: 453

Iterate through keys and values of a Json string in JavaScript

I'm tring to parse a json string that looks like this:

{ "a": [{
    "b": [
        ["c"],
        []
    ], "d": [
        [],
        []
    ], "e": [
        [],
        ["f"]
    ], "g": [
        [],
        ["h", "i"]
    ]
}] }

I'm using the code below to parse it and iterate through the keys and values. However, besides the keys and values that I expect, I get some numbers as keys which I guess are the index numbers of those that don't have any keys. How can I modify the code (pure javascript) so that I only get "a,b,c,d,e,f,g,h,i" as keys and values and nothing more?

var jsonData = JSON.parse("name");
for (var key in jsonData) {
  if (jsonData.hasOwnProperty(key)) {
    // do stuff
  }
}

Upvotes: 1

Views: 205

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Based on example shown you could use a regex on the json string:

let data = {
  "a": [{
    "b": [
      ["c"],
      []
    ],
    "d": [
      [],
      []
    ],
    "e": [
      [],
      ["f"]
    ],
    "g": [
      [],
      ["h", "i"]
    ]
  }]
};

let res = JSON.stringify(data).match(/\w+/g);
console.log(res.join())

Upvotes: 0

tavnab
tavnab

Reputation: 2734

Here's a recursive solution to walk through the data structure. When the parameter is an array, it will iterate and recurse through each element; when the it's an object, it will output each key and recurse through each value; otherwise, it will just output the string representation of the parameter.

var data = { "a": [{
    "b": [
        ["c"],
        []
    ], "d": [
        [],
        []
    ], "e": [
        [],
        ["f"]
    ], "g": [
        [],
        ["h", "i"]
    ]
}] };

function walk(a) {
  if (Array.isArray(a)) {
    a.map(walk);
  } else if (typeof a === 'object') {
    Object.keys(a).forEach(key => {
      console.log(key);
      walk(a[key]);
    });
  } else {
    console.log(a);
  }
}

walk(data);

Upvotes: 1

Related Questions