Javascript JSON 密钥名称中哪些字符有效/无效?

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

Which characters are valid/invalid in a JSON key name?

javascriptjsonobjectkey

提问by Christophe

Are there any forbidden characters in key names, for JavaScript objects or JSON strings? Or characters that need to be escaped?

对于 JavaScript 对象或 JSON 字符串,键名中是否有任何禁用字符?或者需要转义的字符?

To be more specific, I'd like to use "$", "-" and space in key names.

更具体地说,我想在键名中使用“$”、“-”和空格。

回答by Marcelo Cantos

No. Any valid string is a valid key. It can even have "as long as you escape it:

否。任何有效的字符串都是有效的键。"只要你逃脱它,它甚至可以有:

{"The \"meaning\" of life":42}

There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.

在将这些值加载到某些尝试将键与对象字段名称相关联的语言中时,您可能会遇到困难。然而,我不知道有任何这样的案例。

回答by Arun Rana

Following characters must be escaped in JSON data to avoid any problems

必须在 JSON 数据中对以下字符进行转义以避免出现任何问题

‘ single quote

” quote

\ backslash

all control characters like \n \t

' 单引号

“ 引用

\ 反斜杠

所有控制字符,如 \n \t

JSON Parsercan help you to deal with JSON.

JSON Parser可以帮助您处理 JSON。

EDIT: Here's a replacement JSON parser since OP's link is dead

编辑: 这是一个替代的 JSON 解析器,因为 OP 的链接已失效

回答by karns

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

值得一提的是,虽然以数字开头的键是有效的,但它可能会导致一些意想不到的问题。

Example:

例子:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

回答by dolmen

Unicode codepoints U+D800 to U+DFFF must be avoided: they are invalidin Unicode because they are reserved for UTF-16 surrogate pairs. Some JSON encoders/decoders will replace them with U+FFFD. See for example how the Go language and its JSON library deals with them.

必须避免 Unicode 代码点 U+D800 到 U+DFFF:它们在 Unicode中无效,因为它们是为 UTF-16 代理对保留的。一些 JSON 编码器/解码器将用 U+FFFD 替换它们。例如,请参阅Go 语言及其 JSON 库如何处理它们

So avoid "\uD800" to "\uDFFF" alone (not in surrogate pairs).

所以避免单独使用“\uD800”到“\uDFFF”(而不是代理对)。