Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change key name in nested JSON structure

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?

like image 746
user1842231 Avatar asked Nov 22 '12 19:11

user1842231


People also ask

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

How do you remove a key value pair from a JSON object?

How do you remove a key value pair from a JSON object? JsonObject::remove() removes a key-value pair from the object pointed by the JsonObject . If the JsonObject is null, this function does nothing.

Can an object be a key in JSON?

In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”. In Python, "objects" are analogous to the dict type. An important difference, however, is that while Python dictionaries may use anything hashable as a key, in JSON all the keys must be strings.


1 Answers

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/

like image 116
I Hate Lazy Avatar answered Oct 30 '22 18:10

I Hate Lazy