如何重命名JSON键

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

谢谢。

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"}]';

var obj = JSON.parse(json)[0];
obj.id = obj._id;
delete obj._id;

json = JSON.stringify([obj]);

这将json更改为:

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

由于JSON中的名称/值对中的顺序没有意义,因此与您期望的结果相同。

http://stackoverflow.com/questions/13391579/how-to-rename-json-key

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何重命名JSON键