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?
Tl;dr Yes it is.
Empty ValuesNull values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON. 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With