Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a JSON data structure as shown below:

{
    "name": "World",
    "children": [
      { "name": "US",
          "children": [
           { "name": "CA" },
           { "name": "NJ" }
         ]
      },
      { "name": "INDIA",
          "children": [
          { "name": "OR" },
          { "name": "TN" },
          { "name": "AP" }
         ]
      }
 ]
};

I need to change the key names from "name" & "children" to say "key" & "value". Any suggestion on how to do that for each key name in this nested structure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
132 views
Welcome To Ask or Share your Answers For Others

1 Answer

I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question), but if that's removed, then you can use a reviver function to make modifications while parsing the data.

var parsed = JSON.parse(myJSONData, function(k, v) {
    if (k === "name") 
        this.key = v;
    else if (k === "children")
        this.value = v;
    else
        return v;
});

DEMO: http://jsfiddle.net/BeSad/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...