100

I have a JSON object with the following content:

[
  {
    "_id":"5078c3a803ff4197dc81fbfb",
    "email":"user1@gmail.com",
    "image":"some_image_url",
    "name":"Name 1"
  },
  {
    "_id":"5078c3a803ff4197dc81fbfc",
    "email":"user2@gmail.com",
    "image":"some_image_url",
    "name":"Name 2"
  }
]

I want to change the "_id" key to "id" so it would become

[
  {
    "id":"5078c3a803ff4197dc81fbfb",
    "email":"user1@gmail.com",
    "image":"some_image_url",
    "name":"Name 1"
  },
  {
    "id":"5078c3a803ff4197dc81fbfc",
    "email":"user2@gmail.com",
    "image":"some_image_url",
    "name":"Name 2"
  }
]

How would I do that either with Javascript, jQuery or Ruby, Rails?

Thanks.

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
duy
  • 1,890
  • 4
  • 16
  • 20
  • 4
    Parse the JSON, modify the resulting data structure accordingly and convert it back to JSON. Pointers: http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript, http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails, http://stackoverflow.com/questions/2295496/convert-javascript-array-to-json, http://stackoverflow.com/questions/3183786/how-to-convert-a-ruby-hash-object-to-json. – Felix Kling Nov 15 '12 at 04:29

16 Answers16

113
  1. Parse the JSON
const arr = JSON.parse(json);
  1. For each object in the JSON, rename the key:
obj.id = obj._id;
delete obj._id;
  1. Stringify the result

All together:

function renameKey ( obj, oldKey, newKey ) {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
}

const json = `
  [
    {
      "_id":"5078c3a803ff4197dc81fbfb",
      "email":"user1@gmail.com",
      "image":"some_image_url",
      "name":"Name 1"
    },
    {
      "_id":"5078c3a803ff4197dc81fbfc",
      "email":"user2@gmail.com",
      "image":"some_image_url",
      "name":"Name 2"
    }
  ]
`;
   
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );

console.log( updatedJson );
Paul
  • 139,544
  • 27
  • 275
  • 264
31

In this case it would be easiest to use string replace. Serializing the JSON won't work well because _id will become the property name of the object and changing a property name is no simple task (at least not in most langauges, it's not so bad in javascript). Instead just do;

jsonString = jsonString.replace("\"_id\":", "\"id\":");
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • 6
    And what if he will have parameters `"whereToFindIdentification":"id"` ? its never the best way. – Kamil Mar 06 '20 at 12:33
  • 1
    @Kamil the inclusion of the colon to the right in the regex, won't match your example. It implies a field named id, not a value. – Typo Oct 04 '21 at 14:06
26

As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,

var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}];
    
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));

document.write(JSON.stringify(json));

This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split and join instead of replace, because replace will replace only the first occurrence of the string.

Community
  • 1
  • 1
Stranger
  • 10,332
  • 18
  • 78
  • 115
19

JSON.parse has two parameters. The second parameter, reviver, is a transform function that can format the output format we want. See ECMA specification here.

In reviver function:

  • if we return undefined, the original property will be deleted.
  • this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.
const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}]';

const obj = JSON.parse(json, function(k, v) {
    if (k === "_id") {
        this.id = v;
        return; // if return  undefined, orignal property will be removed
    }
    return v;
});

const res = JSON.stringify(obj);
console.log(res)

output:

[{"email":"user1@gmail.com","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"user2@gmail.com","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]
Pylon
  • 698
  • 6
  • 9
  • 6
    This seems like the most correct and clean answer to me. It deals with the problem right at the parsing stage, not ex post like all the others. It also seems like the fastest one, though some benchmarks might be necessary. – Papooch Feb 05 '21 at 10:17
12

Try this:

let jsonArr = [
    {
        "_id":"5078c3a803ff4197dc81fbfb",
        "email":"user1@gmail.com",
        "image":"some_image_url",
        "name":"Name 1"
    },
    {
        "_id":"5078c3a803ff4197dc81fbfc",
        "email":"user2@gmail.com",
        "image":"some_image_url",
        "name":"Name 2"
    }
]

let idModified = jsonArr.map(
    obj => {
        return {
            "id" : obj._id,
            "email":obj.email,
            "image":obj.image,
            "name":obj.name
        }
    }
);
console.log(idModified);
Timisorean
  • 1,388
  • 7
  • 20
  • 30
user7246161
  • 257
  • 3
  • 9
8

If you want to rename all occurrences of some key you can use a regex with the g option. For example:

var json = [{"_id":"1","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}];

str = JSON.stringify(json);

now we have the json in string format in str.

Replace all occurrences of "_id" to "id" using regex with the g option:

str = str.replace(/\"_id\":/g, "\"id\":");

and return to json format:

json = JSON.parse(str);

now we have our json with the wanted key name.

RafaelJan
  • 3,118
  • 1
  • 28
  • 46
3

Is possible, using typeScript

function renameJson(json,oldkey,newkey) {    
 return Object.keys(json).reduce((s,item) => 
      item == oldkey ? ({...s,[newkey]:json[oldkey]}) : ({...s,[item]:json[item]}),{})   
}

Example: https://codepen.io/lelogualda/pen/BeNwWJ

3

By using map function you can do that. Please refer below code.

var userDetails = [{
  "_id":"5078c3a803ff4197dc81fbfb",
  "email":"user1@gmail.com",
  "image":"some_image_url",
  "name":"Name 1"
},{
  "_id":"5078c3a803ff4197dc81fbfc",
  "email":"user2@gmail.com",
  "image":"some_image_url",
  "name":"Name 2"
}];

var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
  id,
  email,
  image,
  name
}));
console.log(formattedUserDetails);
Jitendra Pawar
  • 1,285
  • 15
  • 27
3

If anyone needs to do this dynamically:

const keys = Object.keys(jsonObject);

keys.forEach((key) => {

      // CREATE A NEW KEY HERE
      var newKey = key.replace(' ', '_');

      jsonObject[newKey] = jsonObject[key];
      delete jsonObject[key];
   });

jsonObject will now have the new keys.

IMPORTANT:

If your key is not changed by the replace function, it will just take it out of the array. You may want to put some if statements in there.

LukeVenter
  • 439
  • 6
  • 20
2

If your object looks like this:

obj = {
    "_id":"5078c3a803ff4197dc81fbfb",
    "email":"user1@gmail.com",
    "image":"some_image_url",
    "name":"Name 1"
   }

Probably the simplest method in JavaScript is:

obj.id = obj._id
del object['_id']

As a result, you will get:

obj = {
    "id":"5078c3a803ff4197dc81fbfb",
    "email":"user1@gmail.com",
    "image":"some_image_url",
    "name":"Name 1"
   }
trojek
  • 3,078
  • 2
  • 29
  • 52
1

If you want replace the key of JSON object, use below logic

const student= {
  "key": "b9ed-9c1a04247482",
  "name": "Devaraju",
  "DOB" : "01/02/2000",
  "score" : "A+"
}
let {key, ...new_student} = {...student}
new_student.id= key

console.log(new_student)
Appi Devu
  • 35
  • 1
0

To update oldKey with a newKey in a nested json at any deeper level.

function transformKeys(object, newKey, oldKey) {
    if(Array.isArray(object)){
        object.map((item) => {
            transformKeys(item, newKey, oldKey)
        })
    }
    if(typeof object === 'object' && !Array.isArray(object)){
        Object.keys(object).forEach(key => {
            if (typeof object[key] === 'object') {
                transformKeys(object[key], newKey, oldKey)
            }
            if (key === oldKey) {
                object[newKey] = object[key]
                delete object[key]
            }
        })
    }
}
Shreyak Upadhyay
  • 439
  • 6
  • 10
0

My answer works for nested json like this,


[
  {
    "id": 1,
    "name": "1111111111",
    "children": [
      {
        "id": 2,
        "name": "2222",
      }
    ]
  },
  {
    "id": 3,
    "name": "1",
  },
]

I want replace key 'id' to 'value', and 'name' to 'label' for select componet.

Function:

function renameKeyInJson(json, keys) {
  let dataStr = JSON.stringify(json);
  keys.forEach(e => {
    dataStr = dataStr.replace(new RegExp(`"${e.oldKey}":`, "g"), `"${e.newKey}":`);
  });
  return JSON.parse(dataStr);
}

Usage:

const response = await getAll(bookId);
return renameKeyInJson(response.data, [
  {oldKey: 'name', newKey: 'label'},
  {oldKey: 'id', newKey: 'value'},
]);
Mark Liu
  • 71
  • 1
  • 6
0

My case:

renameJsonKey(json, oldKey, newKey) {
    Map<String, dynamic> newJson = {};
    json.forEach((key, value) {
      if (key == oldKey) {
        newJson.addAll({newKey: json[key]});
      } else {
        newJson.addAll({key: json[key]});
      }
    });
    return newJson;
  }

Change many keys:

renameJsonKeys(json, List<String> oldKeys, List<String> newKeys) {
  Map<String, dynamic> newJson = json;
  for (var i = 0; i < oldKeys.length; i++) {
    newJson = renameJsonKey(newJson, oldKeys[i], newKeys[i]);
  }
  return newJson;
}
Thang Tran
  • 171
  • 1
  • 5
-1

If you want to do it dynamically, for example, you have an array which you want to apply as a key to JSON object:

your Array will be like :

var keys = ["id", "name","Address","Phone"] // The array size should be same as JSON Object keys size

Now you have a JSON Array like:

var jArray = [
  {
    "_id": 1,
    "_name": "Asna",
    "Address": "NY",
    "Phone": 123
  },
  {
    "_id": 2,
    "_name": "Euphoria",
    "Address": "Monaco",
    "Phone": 124
  },
  {
    "_id": 3,
    "_name": "Ahmed",
    "Address": "Mumbai",
    "Phone": 125
  }
]

$.each(jArray ,function(pos,obj){
    var counter = 0;
    $.each(obj,function(key,value){
        jArray [pos][keys[counter]] = value;
        delete jArray [pos][key];
        counter++;
    })  
})

Your resultant JSON Array will be like :

[
  {
    "id": 1,
    "name": "Asna",
    "Address": "NY",
    "Phone": 123
  },
  {
    "id": 2,
    "name": "Euphoria",
    "Address": "Monaco",
    "Phone": 124
  },
  {
    "id": 3,
    "name": "Ahmed",
    "Address": "Mumbai",
    "Phone": 125
  }
]
DogEatDog
  • 2,899
  • 2
  • 36
  • 65
Sufiyan Ansari
  • 1,780
  • 20
  • 22
-1

For a more flexible solution for renaming a key in an object,

Usage:

jsondata = renameKey(jsondata,"_id","id");

Function:

function renameKey(data,oldname,newname)
{
    for (let i = 0; i < data.length; i++) {
        let element = data[i];
        element[newname] = element[oldname];
        delete element[oldname];
    }
    return data;
}

if you need the keys to stay in the same order (like i did) here is a messy solution that I'm sure is poorly optimized.

function renameKey(data,oldname,newname)
{
    for (let i = 0; i < data.length; i++)
    {
        let element = data[i];
        let info = Object.keys(data[i]);

        for (let ii = 0; ii < info.length; ii++)
        {

            let key = info[ii];
            if (key !== oldname)
            {
                let skey = key + "~"; //make temporary key
                element[skey] = element[key]; //copy values to temp key
                delete element[key]; //delete old key
                element[key] = element[skey]; //copy key back to orginal name, preserving its position.
                delete element[skey]; //delete temp key
            }
            else
            {
                element[newname] = element[key];
                delete element[key];
            }
        }
    }
    return data;
}
RustyH
  • 473
  • 7
  • 22