89

我有一个包含以下内容的 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 来做到这一点?

谢谢。

4

13 回答 13

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

于 2012-11-15T04:32:57.470 回答
28

在这种情况下,最容易使用字符串替换。序列化 JSON 将无法正常工作,因为 _id 将成为对象的属性名称,并且更改属性名称并非易事(至少在大多数语言中不是这样,在 javascript 中并没有那么糟糕)。而是做;

jsonString = jsonString.replace("\"_id\":", "\"id\":");
于 2012-11-15T04:31:57.607 回答
24

正如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 格式。但我使用splitandjoin而不是replace, 因为replace只会替换第一次出现的字符串。

于 2016-03-16T08:11:06.447 回答
13

试试这个:

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);
于 2019-06-24T16:52:45.240 回答
9

JSON.parse有两个参数。第二个参数reviver是一个transform函数,可以格式化我们想要的输出格式。请参阅此处的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"}]
于 2019-12-04T12:19:14.827 回答
6

如果要重命名某个键的所有出现,可以使用带有 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。

于 2017-07-03T13:51:30.897 回答
4

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

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);
于 2019-05-23T13:36:34.590 回答
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"
   }
于 2018-04-03T09:54:50.607 回答
3

可以,使用 typeScript

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

示例:https ://codepen.io/lelogualda/pen/BeNwWJ

于 2019-04-29T15:09:32.987 回答
2

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

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其中放置一些语句。

于 2020-04-08T09:16:49.767 回答
1

如果要替换 JSON 对象的键,请使用以下逻辑

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)

于 2021-06-14T05:11:20.537 回答
0

例如,如果您想动态地执行此操作,您有一个数组,您想将其用作 JSON 对象的键:

你的数组会像:

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

现在你有一个 JSON 数组,如:

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
  }
]
于 2017-11-23T11:21:41.257 回答
0

试试这个

function renameKey ( obj, oldKey, newKey ) {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
}
于 2021-08-17T11:08:02.043 回答