-1

Actual Code:

{
    "workbookInformation": {
        "version": "9.1",
        "source-platform": "win"
    },
    "datasources": {
        "filename": "data",
        "caption": "Title",
        "version": "qqq.1",
        "cleaning": "no",
        "inline": "true",
        "validate": "no",
        "class": "excel-direct",
        "interpretationMode": "0"
    }
}

Output I need :

{
    "workbookInformation": {
        "version": "9.1",
        "source-platform": "win"
    },
    "Title": {
        "filename": "data",
        "caption": "Title",
        "version": "qqq.1",
        "cleaning": "no",
        "inline": "true",
        "validate": "no",
        "class": "excel-direct",
        "interpretationMode": "0"
    }
}

caption key value ie. Title needs to be replaced with datasources.

Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
T Sooraj
  • 556
  • 1
  • 5
  • 18
  • 1
    http://stackoverflow.com/questions/13391579/how-to-rename-json-key – M14 Jan 17 '17 at 11:07
  • 3
    Possible duplicate of [JavaScript: Object Rename Key](http://stackoverflow.com/questions/4647817/javascript-object-rename-key) – briosheje Jan 17 '17 at 11:08

3 Answers3

0

You can define a new property directly on an object with Object.defineProperty() and pass descriptor for the property being defined to this method with the result of Object.getOwnPropertyDescriptor():

var obj = {"workbookInformation": {"version": "9.1","source-platform": "win"},"datasources": {"filename": "data","caption": "Title","version": "qqq.1","cleaning": "no","inline": "true","validate": "no","class": "excel-direct","interpretationMode": "0"}};

Object.defineProperty(obj, 'Title', Object.getOwnPropertyDescriptor(obj, 'datasources'));
delete obj.datasources;

console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
-1

Based on your example, you can simply add a new item on the root JSON with the key "Title" and then remove the one with the key "datasources".

Assuming json_obj as your json object:

json_obj[json_obj.datasources.caption] = json_obj.datasources;
delete(json_obj.datasources);
-1

Parse the JSON string into a Javascript object so that you can modify it with ease.

jsObj = JSON.parse(jsonData);

Below I'm creating a new object with the desired keys and finally serialize it again.

jsonData = JSON.stringify({
  workbookInformation: jsObj.workbookInformation,
  Title: jsObj.datasources,
});
  • Please use the [edit] link explain how this code works and don't just give the code, as an explanation is more likely to help future readers. See also [answer]. [source](http://stackoverflow.com/users/5244995) – Jed Fox Jan 17 '17 at 15:00