Which characters are valid/invalid in a JSON key n

2019-01-03 03:04发布

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

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

4条回答
姐就是有狂的资本
2楼-- · 2019-01-03 03:27

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

‘ single quote

” quote

\ backslash

all control characters like \n \t

JSON Parser can help you to deal with JSON.

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

查看更多
太酷不给撩
3楼-- · 2019-01-03 03:36

Unicode codepoints U+D800 to U+DFFF must be avoided: they are invalid in 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.

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

查看更多
Deceive 欺骗
4楼-- · 2019-01-03 03:41

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.

查看更多
We Are One
5楼-- · 2019-01-03 03:53

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

IE:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround
查看更多
登录 后发表回答