javascript 如何使用小写键将 JSON 解析为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14697352/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:20:24  来源:igfitidea点击:

How to parse JSON to object with lower case key

javascriptjqueryjson

提问by texasbruce

I have some JSON data but all the keys are in UPPER case. How to parse them and convert the keys to lower? I am using jQuery.

我有一些 JSON 数据,但所有的键都是大写的。如何解析它们并将键转换为更低?我正在使用 jQuery。

for example:

例如:

JSON data:

JSON 数据:

{"ID":1234, "CONTENT":"HELLO"}

Desired output:

期望的输出:

{id:1234, content:"HELLO"}

回答by Christophe

How about this:

这个怎么样:

json.replace(/"([^"]+)":/g,function(
var str = '{"ID":1234, "CONTENT":"HELLO"}';

var obj = $.parseJSON(str);
$.each(obj, function(i, v) {
    obj[i.toLowerCase()] = v;
    delete obj[i];
});

console.log(obj);
//{id: 1234, content: "HELLO"} 
,){return ('"'+.toLowerCase()+'":');}));

The regex captures the key name $1 and converts it to lower case.

正则表达式捕获键名 $1 并将其转换为小写。

Live demo: http://jsfiddle.net/bHz7x/1/

现场演示:http: //jsfiddle.net/bHz7x/1/

[edit] To address @FabrícioMatté's comment, another demo that only matches word characters: http://jsfiddle.net/bHz7x/4/

[编辑] 为了解决@FabrícioMatté 的评论,另一个仅匹配单词字符的演示:http: //jsfiddle.net/bHz7x/4/

回答by Fabrício Matté

Iterate over the properties and create lowercase properties while deleting old upper case ones:

迭代属性并创建小写属性,同时删除旧的大写属性:

var obj = $.parseJSON(str),
    lowerCased = {};
$.each(obj, function(i, v) {
    lowerCased[i.toLowerCase()] = v;
});

Fiddle

小提琴

Or you can just build a new object from the old one's properties:

或者你可以从旧的属性构建一个新的对象:

function JSON_Lower_keys(J) {
   var ret={};
   $.map(JSON.parse(J),function(value,key){
             ret[key.toLowerCase()]=value;
   })
   return ret;
}

Fiddle

小提琴

References:

参考:

回答by zb'

That is function:

那就是功能:

console.log(JSON_Lower_keys('{"ID":1234, "CONTENT":"HELLO"}'))

that is call:

那就是调用:

var oldObj = { "ID":123, "CONTENT":"HI" }
var keysUpper = Object.keys(oldObj)
var newObj = {}
for(var i in keysUpper){
   newObj[keysUpper[i].toLowerCase()] = oldObj[keysUpper[i]]
}
console.log(JSON.stringify(newObj))

回答by Gabe

You can stick with js and use Objeck.keys()

你可以坚持使用 js 并使用Objeck.keys()

##代码##

Copy and paste into your browser console (F12) >> output: {"id":123,"content":"HI"}

复制并粘贴到浏览器控制台 (F12) >> 输出:{"id":123,"content":"HI"}