JSON.stringify是否在属性上没有引号? [英] JSON.stringify without quotes on properties?
问题描述
我正在使用使用不正确的JSON格式的服务(属性周围没有双引号).所以我需要发送
I'm using a service which uses incorrect JSON format (no double quotes around properties). So I need to send
{ name: "John Smith" }
而不是{ "name": "John Smith" }
无法更改此格式,因为这不是我的服务.
This format cannot be changed as this is not my service.
是否有人知道像上面那样格式化JavaScript对象的字符串化路由?
Anyone know of a stringify routing to format an JavaScript object like above?
推荐答案
var json = '{ "name": "John Smith" }'; //Let's say you got this
json = json.replace(/\"([^(\")"]+)\":/g,"$1:"); //This will remove all the quotes
json; //'{ name: "John Smith" }'
正则表达式将删除所有引号,最重要的是,它不需要库!
The regex will remove all the quotes, and the most important thing is, it does not need a library!
极端情况:
var json = '{ "name": "J\\":ohn Smith" }'
json.replace(/\\"/g,"\uFFFF"); //U+ FFFF
json = json.replace(/\"([^"]+)\":/g,"$1:").replace(/\uFFFF/g,"\\\"");
//'{ name: "J\":ohn Smith" }'
特别感谢Rob W修复它.
Special thanks to Rob W for fixing it.
更新:
在正常情况下,上述正则表达式可以使用,但是从数学上讲,不可能用正则表达式描述JSON格式,使其在每种情况下都可以使用(使用正则表达式无法计算相同数量的大括号.) ,我创建了一个新函数来删除引号,方法是通过本机函数正式解析JSON字符串并重新序列化它:
In normal cases the aforementioned regexp will work, but mathematically it is impossible to describe the JSON format with a regular expression such that it will work in every single cases (counting the same number of curly brackets is impossible with regexp.) Therefore, I have create a new function to remove quotes by formally parsing the JSON string via native function and reserialize it:
function stringify(obj_from_json){
if(typeof obj_from_json !== "object" || Array.isArray(obj_from_json)){
// not an object, stringify using native function
return JSON.stringify(obj_from_json);
}
// Implements recursive object serialization according to JSON spec
// but without quotes around the keys.
let props = Object
.keys(obj_from_json)
.map(key => `${key}:${stringify(obj_from_json[key])}`)
.join(",");
return `{${props}}`;
}
示例: https://jsfiddle.net/DerekL/mssybp3k/
请注意,该代码是用ES6编写的,对于较旧的浏览器,可能需要进行翻译或手动翻译.
Note that the code is written in ES6 and might require transpilation or manual translation for older browsers.
这篇关于JSON.stringify是否在属性上没有引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!