Remove spaces in Json keys [duplicate]

霸气de小男生 提交于 2019-12-22 01:19:12

问题


I have my json in the below format

[{
    "Id": "ALFKI",
    "Contact Name": "Maria Anders",
    "Contact Title": "Sales Representative",
    "City": "Berlin",
    "Slider": 10
}, {
    "Id": "ANATR",
    "Contact Name": "Ana Trujillo",
    "Contact Title": "Owner",
    "City": "México D.F.",
    "Slider": 5
}]

My desired Json

[{
    "Id": "ALFKI",
    "ContactName": "Maria Anders",
    "ContactTitle": "Sales Representative",
    "City": "Berlin",
    "Slider": 10
}, {
    "Id": "ANATR",
    "ContactName": "Ana Trujillo",
    "ContactTitle": "Owner",
    "City": "México D.F.",
    "Slider": 5
}]

Kendo grid doesn't accept Key names with spaces


回答1:


You can use JSON.stringify(), JSON.parse(), String.prototype.replace() with RegExp /\s(?=\w+":)/g to match space character followed by one or more word characters followed by " followed by :

var arr = [{
    "Id": "ALFKI",
    "Contact Name": "Maria Anders",
    "Contact Title": "Sales Representative",
    "City": "Berlin",
    "Slider": 10
}, {
    "Id": "ANATR",
    "Contact Name": "Ana Trujillo",
    "Contact Title": "Owner",
    "City": "México D.F.",
    "Slider": 5
}];

arr = JSON.parse(JSON.stringify(arr).replace(/\s(?=\w+":)/g, ""));

console.log(arr);


来源:https://stackoverflow.com/questions/44204765/remove-spaces-in-json-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!