[json] How to rename JSON key

I have a JSON object with the following content:

[
  {
    "_id":"5078c3a803ff4197dc81fbfb",
    "email":"[email protected]",
    "image":"some_image_url",
    "name":"Name 1"
  },
  {
    "_id":"5078c3a803ff4197dc81fbfc",
    "email":"[email protected]",
    "image":"some_image_url",
    "name":"Name 2"
  }
]

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

[
  {
    "id":"5078c3a803ff4197dc81fbfb",
    "email":"[email protected]",
    "image":"some_image_url",
    "name":"Name 1"
  },
  {
    "id":"5078c3a803ff4197dc81fbfc",
    "email":"[email protected]",
    "image":"some_image_url",
    "name":"Name 2"
  }
]

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

Thanks.

This question is related to json

The answer is


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.


JSON.parse has two parameters. The second parameter, reviver, is a transform function that can be formatted 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":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","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":"[email protected]","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"[email protected]","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]

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


Try this:

let jsonArr = [
    {
        "_id":"5078c3a803ff4197dc81fbfb",
        "email":"[email protected]",
        "image":"some_image_url",
        "name":"Name 1"
    },
    {
        "_id":"5078c3a803ff4197dc81fbfc",
        "email":"[email protected]",
        "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);

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

_x000D_
_x000D_
var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}];_x000D_
    _x000D_
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));_x000D_
_x000D_
document.write(JSON.stringify(json));
_x000D_
_x000D_
_x000D_

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.


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

var userDetails = [{
  "_id":"5078c3a803ff4197dc81fbfb",
  "email":"[email protected]",
  "image":"some_image_url",
  "name":"Name 1"
},{
  "_id":"5078c3a803ff4197dc81fbfc",
  "email":"[email protected]",
  "image":"some_image_url",
  "name":"Name 2"
}];

var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
  id,
  email,
  image,
  name
}));
console.log(formattedUserDetails);

If your object looks like this:

obj = {
    "_id":"5078c3a803ff4197dc81fbfb",
    "email":"[email protected]",
    "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":"[email protected]",
    "image":"some_image_url",
    "name":"Name 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
  }
]

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\":");

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":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"[email protected]","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.