223

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
  • I think partially this answer has to do with the way you're encoding. For example, UTF8 has different characters allowed versus ANSI. Dec 30, 2011 at 4:00
  • 5
    You can use any 'key' you want in JS using the obj['whatever'] notation. But only regular alphanumeric keys can be used for the obj.whatever version.
    – Marc B
    Dec 30, 2011 at 4:05
  • 4
    @invalidsyntax: JSON is Unicode by definition. Also, ANSI isn't an encoding, it's a character set, so the comparison should be Unicode-vs-ANSI, not UTF-8-vs-ANSI. Dec 30, 2011 at 4:06
  • 1
    Old discussion but, ASCII (what people often refer to by ANSI) is an encoding and on top of that it also defines a character set.
    – Trinidad
    Feb 23, 2019 at 22:20

5 Answers 5

231

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.

15
  • 1
    Thx! Any other characters that would need to be escaped? Like : or ; ?
    – Christophe
    Dec 30, 2011 at 4:18
  • 15
    Not those. Whatever needs escaping in JavaScript generally needs it in JSON. Best to get it from the horse's mouth, though, at json.org. It takes about one minute to read the entire spec end-to-end. Dec 30, 2011 at 4:21
  • 5
    This is not a good answer imho. Which kind of characters need to be escaped? Which characters can be escaped, but don't have to be escaped?
    – Daniel W.
    Dec 18, 2015 at 12:20
  • 2
    Can anyone clarify if this includes things like the Unicode null character (U+0000, plain "null byte" in UTF-8), etc? The both json.org and the linked official/formal ECMA specification PDF seem to imply that yes, those are valid in JSON, even in their literal forms (not just in the \u four-hex-digits form).
    – mtraceur
    Jun 16, 2016 at 13:13
  • 1
    @mtraceur I was wondering the same thing. I tested in chrome's console and it doesn't like a key with null terminators in it. puu.sh/zJMIS/3d15c6d8e5.png It may not be mentioned in the spec, but don't expect parsers to accept it. best to avoid any ascii control characters I think. Mar 17, 2018 at 20:58
74

The following characters must be escaped in JSON data to avoid any problems:

  • " (double quote)
  • \ (backslash)
  • all control characters like \n, \t

JSON Parser can help you to deal with JSON.

6
  • 7
    Hi Arun, single quotes do not need to be escaped. Infact escaping them will cause strict JSON parsers to throw an exception. Refer to the string section of json.org Of course however you will need to escape them when inside a JSON string (but not the JSON itself). Jan 4, 2014 at 17:59
  • 7
    @AlexKey you're completely right! Arun, you can check this on jsonlint.com by testing the JSON { "singlequotetest": "something here isn\'t right"} versus { "singlequotetest": "Fixing here what wasn't right"}
    – Adriano
    Sep 23, 2014 at 10:51
  • @Arun Rana - no worries. Sep 23, 2014 at 12:55
  • 6
    { "*~@#$%^&*()_+=><?/": "is a valid json" }
    – Abhi
    Oct 7, 2014 at 4:24
  • 72
    {"🐶🔫": "not nice, but still valid json"} Dec 31, 2015 at 2:02
25

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
6
  • 6
    I really hope that, in this 2017/18 age of Microsoft, they are regretful of all the pain that they have inflicted.
    – monsto
    Dec 8, 2017 at 21:47
  • 1
    Look at their metrics ID parameters: dev.applicationinsights.io/apiexplorer/… ---15 or 20 of their fields have multiple forward slashes in their json field names. While Karns solution works for a specific field, I can't seem to get it to work for a sub-field of 1tile. E.g., a subsequent dot returns undefined for me. Dec 22, 2017 at 3:21
  • This should be the best answer
    – Joe Elia
    May 8, 2020 at 21:12
  • 3
    −1. This is not an answer to the question. At best, it should be a comment. The syntax of JavaScript identifiers is a whole other topic. Jul 1, 2022 at 14:59
  • 1
    @Philippe-AndréLorin OP's question is tagged Json and Javascript
    – c z
    Jul 10 at 11:21
15

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).

1
1

Both JSON and JavaScript allow arbitrary strings as object property names, according to their own language definitions. The most recent JSON language definition documents are RFC 8259 for JSON and ECMA-262 for JavaScript.

The characters needing escaping in keys are the characters that are required to be escaped in any string in the language. These are also given in the language definition documents. For JSON, the characters required to be escaped are the quotation mark, backslash, and control characters. For Javascript, the characters requiring escaping are the quote character matching the enclosing quotes (single or double), backslash, carriage return, and line feed.

For your specific example, all of "$", "-" and space are allowed as keys of both JSON & JavaScript objects with no escaping required.

Object property names

Per RFC 8259, there are no limits imposed on the value of strings used as JSON object names:

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

   object = begin-object [ member *( value-separator member ) ]
            end-object

   member = string name-separator value

Regarding JavaScript, ECMA-262 explicitly states that all strings are valid object property names:

A property key value is either an ECMAScript String value or a Symbol value. All String and Symbol values, including the empty String, are valid as property keys. A property name is a property key that is a String value.

String escaping

RFC 8259 lists the characters that must be escaped in JSON:

All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

ECMA-262 lists the characters that must be escaped in JavaScript:

A string literal is 0 or more Unicode code points enclosed in single or double quotes. […] All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED).

The closing quote code point would be " if the string is enclosed in double quotes, and ' if it is enclosed in single quotes.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.