How to iterate over a JSONObject?

后端 未结 16 1885
孤街浪徒
孤街浪徒 2020-11-22 04:17

I use a JSON library called JSONObject (I don\'t mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSO

16条回答
  •  被撕碎了的回忆
    2020-11-22 04:42

    The simpler approach is (just found on W3Schools):

    let data = {.....}; // JSON Object
    for(let d in data){
        console.log(d); // It gives you property name
        console.log(data[d]); // And this gives you its value
    }
    

    UPDATE

    This approach works fine until you deal with the nested object so this approach will work.

    const iterateJSON = (jsonObject, output = {}) => {
      for (let d in jsonObject) {
        if (typeof jsonObject[d] === "string") {
          output[d] = jsonObject[d];
        }
        if (typeof jsonObject[d] === "object") {
          output[d] = iterateJSON(jsonObject[d]);
        }
      }
      return output;
    }
    

    And use the method like this

    let output = iterateJSON(your_json_object);
    

提交回复
热议问题