Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an empty string a valid JSON key?

Is a JSON object having an empty string as a key valid, for example { "c": "x", "": "y" }?

It certainly seems to be, or at least it doesn't seem to break the web if I using it in a browser as per this jsfiddle having the following code:

var a = { "a": "x", "b": "y" };
var b = { "c": "x", "": "y" };
var c = JSON.stringify(a);
var d = JSON.stringify(b);
console.log(c);
console.log(d);
var e = JSON.parse(c);
var f = JSON.parse(d);
console.log(e);
console.log(f);

There is a good reason why I need (want) to use an empty string for a key, but am I just asking for trouble, in terms of browser compatibility and future-proofing?

like image 643
drmrbrewer Avatar asked Nov 18 '19 14:11

drmrbrewer


People also ask

Can JSON have empty string as key?

Tl;dr Yes it is.

Is empty string valid JSON?

Empty ValuesNull values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON. JSON.

Is empty JSON a valid JSON?

In JSON Schema, an empty object is a completely valid schema that will accept any valid JSON. You can also use true in place of the empty object to represent a schema that matches anything, or false for a schema that matches nothing.

Is an empty string valid?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.


1 Answers

Tl;dr Yes it is.


The ECMA spec states (highlighting is mine not the specs):

6 Objects

.....

The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs.

The section on how a string is formatted also allows you to go directly from " to the closing ":

9 String

enter image description here

like image 97
Liam Avatar answered Oct 24 '22 03:10

Liam