Javascript JSON.stringify 在属性上没有引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11233498/
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
JSON.stringify without quotes on properties?
提问by jadent
I'm using a service which uses incorrect JSON format (no double quotes around properties). So I need to send
我使用的服务使用了不正确的 JSON 格式(属性周围没有双引号)。所以我需要发送
{ name: "John Smith" }
instead of { "name": "John Smith" }
{ name: "John Smith" }
代替 { "name": "John Smith" }
This format cannot be changed as this is not my service.
由于这不是我的服务,因此无法更改此格式。
Anyone know of a stringify routing to format an JavaScript object like above?
任何人都知道字符串化路由来格式化上面的 JavaScript 对象?
回答by u283863
This simple regular expression solution works to unquote JSON property names in most cases:
在大多数情况下,这个简单的正则表达式解决方案可用于取消引用 JSON 属性名称:
const object = { name: 'John Smith' };
const json = JSON.stringify(object); // {"name":"John Smith"}
console.log(json);
const unquoted = json.replace(/"([^"]+)":/g, ':');
console.log(unquoted); // {name:"John Smith"}
Extreme case:
极端情况:
var json = '{ "name": "J\":ohn Smith" }'
json.replace(/\"/g,"\uFFFF"); // U+ FFFF
json = json.replace(/"([^"]+)":/g, ':').replace(/\uFFFF/g, '\\"');
// '{ name: "J\":ohn Smith" }'
Special thanks to Rob W for fixing it.
特别感谢 Rob W 修复它。
Limitations
限制
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:
在正常情况下,上述正则表达式会起作用,但从数学上讲,用正则表达式描述 JSON 格式是不可能的,这样它就可以在每种情况下都起作用(用正则表达式计算相同数量的大括号是不可能的。)因此,我有创建一个新函数,通过原生函数正式解析 JSON 字符串并重新序列化它来删除引号:
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}}`;
}
回答by fino
It looks like this is a simple Object toString method that you are looking for.
看起来这是您正在寻找的一个简单的 Object toString 方法。
In Node.js this is solved by using the util object and calling util.inspect(yourObject). This will give you all that you want. follow this link for more options including depth of the application of method. http://nodejs.org/api/util.html#util_util_inspect_object_options
在 Node.js 中,这是通过使用 util 对象并调用 util.inspect(yourObject) 来解决的。这会给你你想要的一切。点击此链接以获取更多选项,包括方法应用的深度。http://nodejs.org/api/util.html#util_util_inspect_object_options
So, what you are looking for is basically an object inspector not a JSON converter. JSON format specifies that all properties must be enclosed in double quotes. Hence there will not be JSON converters to do what you want as that is simply not a JSON format.Specs here: https://developer.mozilla.org/en-US/docs/Using_native_JSON
所以,你要找的基本上是一个对象检查器,而不是一个 JSON 转换器。JSON 格式指定所有属性都必须用双引号括起来。因此,不会有 JSON 转换器来执行您想要的操作,因为这根本不是 JSON 格式。此处的规范:https: //developer.mozilla.org/en-US/docs/Using_native_JSON
Object to string or inspection is what you need depending on the language of your server.
根据您的服务器的语言,您需要对象到字符串或检查。
回答by Rob W
You can look at the source code of json2.js
a parser created by the one who defined the JSON format. Look for quote
function calls: these surround a value by quotes. Keys are quoted at lines 326and 338.
您可以查看由定义 JSON 格式的人创建的解析器的源代码。查找函数调用:这些函数用引号将值括起来。键在第326和338行引用。json2.js
quote
Do not include the library after the modification. Instead only take the relevant (stringify
) part, or at least replace JSON
with something else, eg. FAKEJSON
.
修改后不要包含库。而是只取相关的 ( stringify
) 部分,或者至少JSON
用其他东西替换,例如。FAKEJSON
.
For example, an object FAKEJSON
which only defined stringify
: http://jsfiddle.net/PYudw/
例如,FAKEJSON
只定义了一个对象stringify
:http: //jsfiddle.net/PYudw/
回答by Bergi
Try to use the servive with JSONP, I guess they offer it when using this format.
尝试将 servive 与 JSONP 一起使用,我猜他们在使用这种格式时会提供它。
Else, file them a detailed bug report including a good argumentation why the should conform to the standard. Any other solution than eliminating the source problem is no real solution.
否则,向他们提交一份详细的错误报告,包括一个很好的论证为什么应该符合标准。除了消除源问题之外,任何其他解决方案都不是真正的解决方案。
A quick-n-dirty fix might be to pipe the string through a regex before parsing it:
一个快速的解决方法可能是在解析字符串之前通过正则表达式传输字符串:
var obj = JSON.parse(str.replace(/(\{|,)\s*(.+?)\s*:/g, ' "":'));
Or you try to adjust a existing javascript JSON parser (like this one) if you want a more syntactical parse.
或者,如果您想要更语法化的解析,您可以尝试调整现有的 javascript JSON 解析器(例如这个)。
回答by user1543276
Found a good NPM paackage to do just this:
找到了一个很好的 NPM 包来做到这一点:
https://www.npmjs.com/package/stringify-object
https://www.npmjs.com/package/stringify-object
const stringify = require('stringify-object')
let prettyOutput = stringify(json);
Works pretty well.
工作得很好。
回答by Adel Bachene
@Derek朕會功夫 Thanks for sharing this method, I'de like to share my code which supports stringifying an array of objects as well.
@Derek我会功夫感谢分享这个方法,我想分享我的代码,它也支持对对象数组进行字符串化。
export const stringifyObjectWithNoQuotesOnKeys = (obj_from_json) => {
// In case of an array we'll stringify all objects.
if (Array.isArray(obj_from_json)) {
return `[${
obj_from_json
.map(obj => `${stringifyObjectWithNoQuotesOnKeys(obj)}`)
.join(",")
}]` ;
}
// not an object, stringify using native function
if(typeof obj_from_json !== "object" || obj_from_json instanceof Date || obj_from_json === null){
return JSON.stringify(obj_from_json);
}
// Implements recursive object serialization according to JSON spec
// but without quotes around the keys.
return `{${
Object
.keys(obj_from_json)
.map(key => `${key}:${stringifyObjectWithNoQuotesOnKeys(obj_from_json[key])}`)
.join(",")
}}`;
};
回答by user1649339
Your inherited syntax should be easily eaten by YAML, which is a superset of JSON.
你继承的语法应该很容易被 YAML 吃掉,YAML 是 JSON 的超集。
Try the JavaScript YAML parser and dumper: http://nodeca.github.com/js-yaml/
尝试 JavaScript YAML 解析器和转储器:http: //nodeca.github.com/js-yaml/
回答by Martin Drapeau
CSVJSON's JSON Beautifierhas an option to drop quotes on keys. If you want just the code, you can copy it from the GitHub repo. I modified Douglas Crockford's JSON2to add support for that.
CSVJSON 的 JSON Beautifier可以选择在键上去掉引号。如果您只需要代码,可以从 GitHub 存储库中复制它。我修改了 Douglas Crockford 的 JSON2以添加对此的支持。
回答by Inigo
Use JSON5.stringify
用 JSON5.stringify
JSON5is a superset of JSON that allows ES5 syntax, including unquotedproperty keys. The JSON5 reference implementation (json5
npm package) provides a JSON5
object that has the same methods with the same args and semantics as the built-in JSON
object.
JSON5是 JSON 的超集,它允许使用 ES5 语法,包括不带引号的属性键。JSON5 参考实现(json5
npm 包)提供了一个JSON5
对象,该对象具有与内置JSON
对象相同的方法和相同的参数和语义。
It is highly likely that the service you are using is using this library.
您正在使用的服务很可能正在使用此库。