如何重命名 JSON 密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13391579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rename JSON key
提问by duy
I have a JSON object with the following content:
我有一个包含以下内容的 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"
}
]
I want to change the "_id" key to "id" so it would become
我想将“_id”键更改为“id”,这样它就会变成
[
{
"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?
我将如何使用 Javascript、jQuery 或 Ruby、Rails 做到这一点?
Thanks.
谢谢。
回答by Paul
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"}]';
var obj = JSON.parse(json)[0];
obj.id = obj._id;
delete obj._id;
json = JSON.stringify([obj]);
This changes json to:
这将 json 更改为:
[{"email":"[email protected]","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"}]
Since order doesn't have meaning in a name/value pair in JSON, this is the same as your desired result.
由于顺序在 JSON 中的名称/值对中没有意义,因此这与您想要的结果相同。
回答by evanmcdonnal
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;
在这种情况下,最容易使用字符串替换。序列化 JSON 将无法正常工作,因为 _id 将成为对象的属性名称,而更改属性名称并不是一项简单的任务(至少在大多数语言中不是这样,在 javascript 中并没有那么糟糕)。而是做;
jsonString = jsonString.replace("\"_id\":", "\"id\":");
回答by Stranger
As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,
正如evanmcdonnal所提到的,最简单的解决方案是将其作为字符串而不是 JSON 处理,
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"}];
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 splitand joininstead of replace, because replacewill replace only the first occurrence of the string.
这会将给定的 JSON 数据转换为字符串并将“_id”替换为“id”,然后将其转换回所需的 JSON 格式。但我使用splitandjoin而不是replace, 因为replace只会替换字符串的第一次出现。
回答by user7246161
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);
回答by RefaelJan
If you want to rename all occurrencesof some key you can use a regex with the g option. For example:
如果你想重命名某个键的所有出现,你可以使用带有 g 选项的正则表达式。例如:
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.
现在我们在str中有字符串格式的json。
Replace all occurrences of "_id" to "id" using regex with the goption:
使用带有g选项的正则表达式将所有出现的“_id”替换为“id” :
str = str.replace(/\"_id\":/g, "\"id\":");
and return to json format:
并返回json格式:
json = JSON.parse(str);
now we have our json with the wanted key name.
现在我们有了我们想要的密钥名称的 json。
回答by Aurelio Gualda
Is possible, using typeScript
有可能,使用 typeScript
function renameJson(json,oldkey,newkey) {
return Object.keys(json).reduce((s,item) =>
item == oldkey ? ({...s,[newkey]:json[oldkey]}) : ({...s,[item]:json[item]}),{})
}
回答by Jitendra Pawar
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);
回答by Pylon
JSON.parsehas two parameters. The second parameter, reviver, is a transform function that can be formatted output format we want. See ECMA specification here.
JSON.parse有两个参数。第二个参数reviver是一个转换函数,可以格式化输出我们想要的格式。请参阅此处的ECMA 规范。
In reviver function:
在复活功能中:
- if we return undefined, the original property will be deleted.
thisis 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.
- 如果我们返回 undefined,原始属性将被删除。
this是包含作为此函数处理的属性的对象,属性名称作为字符串,属性值作为此函数的参数。
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"}]
回答by LukeVenter
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];
});
jsonObjectwill now have the new keys.
jsonObject现在将拥有新密钥。
IMPORTANT:
重要的:
If your key is not changed by the replacefunction, it will just take it out of the array. You may want to put some ifstatements in there.
如果您的密钥没有被replace函数更改,它只会将其从数组中取出。你可能想if在那里放一些语句。
回答by trojek
If you object looks like this:
如果你的对象看起来像这样:
obj = {
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
}
Probably the simplest method in JavaScript is:
JavaScript 中最简单的方法可能是:
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"
}

