Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there limitations for key-names in JSON-files?

I was wondering if there are any limitations for key-names in the JSON-format. The keys in most examples I have seen so far matched the RegExp [a-zA-Z\-_].

{
  "name": "My Name",
  "phone-number": 123
}

But is it also valid to use spaces, slashes, umlauts, etc?

{
  "name with spaces": "My Name",
  "[phöne-/mobilé-] number": 123,
  "/\- \" )": "nothing",
  "a \"good\" name" : "empty"
}
like image 546
Edward Avatar asked Sep 11 '25 12:09

Edward


2 Answers

No, there's no restriction. json.org contains the specification for JSON. Keys in object can be any string, and the production for string says that it can contain any Unicode character, as well as various escape sequences.

However, the specification for the backslash character in strings says that it can only be followed by certain characters that form designated escape sequences. \- is not one of these escape sequences, so "/\- \" )" is not a valid JSON string, and hence is not a valid key in an object. It should be written as "/- \" )". (Many languages allow you to put backslash before any character; some treat it as a literal backslash if it doesn't start an escape sequence, while others treat it as redundantly marking the following character as literal -- JSON avoids taking sides by disallowing it.)

like image 79
Barmar Avatar answered Sep 14 '25 05:09

Barmar


Everything except the third string are valid json keys. If you have any doubts about some specific key - you can always use JSON validators like this: http://jsonformatter.curiousconcept.com/ If you are interested in the specification of JSON - you can find it on json.org

like image 39
ZuoLi Avatar answered Sep 14 '25 05:09

ZuoLi