如何重命名JSON密钥


76

我有一个具有以下内容的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"
  }
]

我想将“ _id”键更改为“ id”,这样它将变成

[
  {
    "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"
  }
]

如何使用Javascript,jQuery或Ruby,Rails做到这一点?

谢谢。


Answers:


98
  1. 解析JSON
const arr = JSON.parse(json);
  1. 对于JSON中的每个对象,重命名键:
obj.id = obj._id;
delete obj._id;
  1. 字符串化结果

全部一起:

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 );


5
如果我想将更改应用于json中的所有_id怎么办?
truongnm '16

1
@truongnm循环播放
Viswanath Lekshmanan

2
另外,如果您想使用带有空格的键,则可以像这样添加它obj [“ my id”] = obj.id
catchiecop

27

在这种情况下,使用字符串替换将是最简单的。序列化JSON不能很好地工作,因为_id将成为对象的属性名称,并且更改属性名称并不是一件容易的事(至少在大多数语言中并非如此,在javascript中还不是很糟糕)。相反,只是做;

jsonString = jsonString.replace("\"_id\":", "\"id\":");

2
如果他有参数"whereToFindIdentification":"id"怎么办?这绝不是最好的方法。
卡米尔

22

evanmcdonnal所述,最简单的解决方案是将其作为字符串而不是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));

这会将给定的JSON数据转换为字符串,并将“ _id”替换为“ id”,然后将其转换回所需的JSON格式。但是我使用splitjoin代替replace,因为replace它将仅替换字符串的第一次出现。


1
非常感谢Stranger先生,它对我有很大帮助。
Chetan S. Choudhary

1
干净,简短,解释清楚。大!
安德里亚斯

11

尝试这个:

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);

5

如果要重命名所有出现的某个键,可以使用带有g选项的正则表达式。例如:

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);

现在我们在str中使用字符串格式的json。

使用带有g选项的正则表达式将所有出现的“ _id”替换为“ id” :

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

并返回json格式:

json = JSON.parse(str);

现在我们有了带有所需键名的json。


3
如果任何地方都包含要替换的键名的值,则此方法将不起作用,因为它也会替换该键名。
卡拉瑟

好点,但边缘情况。替换文本时始终需要谨慎
-RefaelJan


3

通过使用地图功能,您可以做到这一点。请参考下面的代码。

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);

3

JSON.parse有两个参数。第二个参数reviver是一个转换函数,可以将其格式化为所需的输出格式。请参阅此处的ECMA规范。

在齐磊功能中:

  • 如果返回undefined,则原始属性将被删除。
  • this 是包含正在作为此函数处理的属性,属性名称为字符串,属性值为该函数的参数的对象。
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)

输出:

[{"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"}]

3

如果您的对象看起来像这样:

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

JavaScript中最简单的方法可能是:

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

结果,您将获得:

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

1

如果有人需要动态执行此操作:

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 现在将具有新密钥。

重要:

如果replace函数未更改您的密钥,它将直接从数组中取出。您可能需要在其中添加一些if语句。


0

例如,如果要动态执行此操作,则有一个要用作JSON对象键的数组:

你的数组就像:

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

现在您有了一个JSON Array,如下所示:

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++;
    })  
})

您生成的JSON数组将类似于:

[
  {
    "id": 1,
    "name": "Asna",
    "Address": "NY",
    "Phone": 123
  },
  {
    "id": 2,
    "name": "Euphoria",
    "Address": "Monaco",
    "Phone": 124
  },
  {
    "id": 3,
    "name": "Ahmed",
    "Address": "Mumbai",
    "Phone": 125
  }
]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.