Can json have only key without value? - json

Json format defines keys and values. And how about the following
{
"Kill"
}
Is it an acceptable json format?

No, in JSON notation, an object is an unordered set of key/value pairs, and both the key and the value are required elements.
If the object you've shown is the only thing you want to have in your JSON text, you could just remove the object wrapper:
"Kill"
That's perfectly valid JSON. (There was a time when JSON was defined as requiring the outermost element to be an object or an array, but that hasn't been true for many, many years.)

The original JSON introduction is extremely straight-forward, including diagrams of the possible constructions. Among the text content is this:
An object is an unordered set of name/value pairs. An object begins with { left brace and ends with } right brace. Each name is followed by : colon and the name/value pairs are separated by , comma.
The later ECMA-404 standard includes similar wording:
An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs. A name is a string. A single colon token follows each name, separating the name from the value. A single
comma token separates a value from a following name.
The IETF standard, RFC 8259 puts it this way:
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.
In every case, note that every key is followed by a colon and a value. Since there is no colon following the key in your example, it is not valid JSON.

Related

Does the JSON structure have to always be the exact same layout?

so here is a little example of something I'd like to know if it matters or not.
Is this the same:
{
{
"Statement" : "BankTrans1",
"amount" : 512.46,
"Bcode" : "EWT5620"
}
}
as this:
{
{
"Bcode" : "EWT5620",
"amount" : 512.46,
"Statement" : "BankTrans1"
}
}
Would the JSON Schema still parse the data even if its not in the same order? Apologies if this is a nooby question, just wanted to confirm.
Thank you for your time.
Both structures are the same. The order does not matter here as values will be accessed by the keys.
FROM http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs.
A name is a string. A single colon token follows each name, separating the name from the value. A single
comma token separates a value from a following name. 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. These are all semantic considerations that may be defined by
JSON processors or in specifications defining specific uses of JSON for data interchange.
In JS try var obj = JSON.parse(text); and then print the obj, if you are getting same results for both your cases then text is getting parsed irrespective of the key order, else not.

In a key value pair, can a key be another k-v pair?

I know the following JSON objects are valid KV pairs:
{a:1,b:45,h:98}
{a:1,b:45,h:[a:1,b:45,h:98]}
-- Value of Key h is another array of KVP
{a:1,b:45,h:[98,97,65,43]}
But is this valid:
{a:1,b:45,{a:1,b:45,h:98}:98}
context is MongoDB's JSON objects
No. MongoDB uses JSON syntax and stores objects as JSON (well, technically BSON). json.org says very explicitly that the syntax for objects -- the things between {}, is string : value. In the same document, it goes on to say:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes
This would preclude you from using an object literal as a key.
I think that if you think about it enough you would realize that it doesn't make sense to use anything other than a string as a key anyway.

Is a value on its own a valid JSON string?

In a JSON API, is it valid to return single values such as 123, "somestring" or null?
I read the JSON spec, which states that:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
but I'm not clear if this means that only objects and arrays are valid JSON, or if values on their own are valid too (i.e. will be parsed correctly by any compliant parser).
Any idea?
No, it's not valid. Check this out if you want to experiment with anything.
The two structures are as follows:
Some kind of key-value pair:
{
"key": "value"
}
or an array
['value', 'value']
or any combination of the two
[{"key":"value"}, "value", ["a", "list", {"another":['list']}]]
However, the values on their own (numbers, strings, booleans, etc., are not valid on their own.
Is 123 a collection of name/value pairs? No, it is not.
Is 123 an ordered list of values? No, it is not.
Thus, 123 is not a valid JSON string.
Edit: As gdoron suggested, you could use a JSON parser (e.g. here) to test your single value.

Can JSON start with "["?

From what I can read on json.org, all JSON strings should start with { (curly brace), and [ characters (square brackets) represent an array element in JSON.
I use the json4j library, and I got an input that starts with [, so I didn't think this was valid JSON. I looked briefly at the JSON schema, but I couldn't really find it stated that a JSON file cannot start with [, or that it can only start with {.
JSON can be either an array or an object. Specifically off of json.org:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record,
struct, dictionary, hash table,
keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an
array, vector, list, or sequence.
It then goes on to describe the two structures as:
Note that the starting and ending characters are curly brackets and square brackets respectively.
Edit
And from here: http://www.ietf.org/rfc/rfc4627.txt
A JSON text is a sequence of tokens.
The set of tokens includes six
structural characters, strings,
numbers, and three literal names.
A JSON text is a serialized object or array.
Update (2014)
As of March 2014, there is a new JSON RFC (7159) that modifies the definition slightly (see pages 4/5).
The definition per RFC 4627 was: JSON-text = object / array
This has been changed in RFC 7159 to: JSON-text = ws value ws
Where ws represents whitespace and value is defined as follows:
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:
false null true
So, the answer to the question is still yes, JSON text can start with a square bracket (i.e. an array). But in addition to objects and arrays, it can now also be a number, string or the values false, null or true.
Also, this has changed from my previous RFC 4627 quote (emphasis added):
A JSON text is a sequence of tokens. The set of tokens includes six
structural characters, strings, numbers, and three literal names.
A JSON text is a serialized value. Note that certain previous
specifications of JSON constrained a JSON text to be an object or an
array. Implementations that generate only objects or arrays where a
JSON text is called for will be interoperable in the sense that all
implementations will accept these as conforming JSON texts.
If the string you are parsing begins with a left brace ([) you can use JSONArray.parse to get back a JSONArray object and then you can use get(i) where i is an index from 0 through the returned JSONArray's size()-1.
import java.io.IOException;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
public class BookListTest {
public static void main(String[] args) {
String jsonBookList = "{\"book_list\":{\"book\":[{\"title\":\"title 1\"},{\"title\":\"title 2\"}]}}";
Object book_list;
try {
book_list = JSONObject.parse(jsonBookList);
System.out.println(book_list);
Object bookList = JSONObject.parse(book_list.toString()).get("book_list");
System.out.println(bookList);
Object books = JSONObject.parse(bookList.toString()).get("book");
System.out.println(books);
JSONArray bookArray = JSONArray.parse(books.toString());
for (Object book : bookArray) {
System.out.println(book);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Which produced output like:
{"book_list":{"book":[{"title":"title 1"},{"title":"title 2"}]}}
{"book":[{"title":"title 1"},{"title":"title 2"}]}
[{"title":"title 1"}, {"title":"title 2"}]
{"title":"title 1"}
{"title":"title 2"}
Note: if you attempted to call JSONObject.parse(books.toString()); you would get the error you encountered:
java.io.IOException: Expecting '{' on line 1, column 2 instead, obtained token: 'Token: ['
JSON.ORG WEBSITE SAYS ....
https://www.json.org/
The site clearly states the following:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most languages, this is realized as
an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on these forms:
OBJECT:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
{string: value, string: value}
ARRAY:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
[value, value, value ….]
VALUE:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
STRING:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
NUMBER:
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
ABOUT WHITESPACE:
Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.
Short answer is YES
In a .json file you can put Numbers (even just 10), Strings (even just "hello"), Booleans (true, false), Null (even just null), arrays and objects.
https://www.json.org/json-en.html
Using just Numbers, Strings, Booleans and Null are not logical because in .jon files we use more complicated structured data like arrays and object (mostly mix nested versions).
Below you can find a sample JSON data with array of object and start with "["
https://jsonplaceholder.typicode.com/posts

Do the JSON keys have to be surrounded by quotes?

Example:
Is the following code valid against the JSON Spec?
{
precision: "zip"
}
Or should I always use the following syntax? (And if so, why?)
{
"precision": "zip"
}
I haven't really found something about this in the JSON specifications. Although they use quotes around their keys in their examples.
Yes, you need quotation marks. This is to make it simpler and to avoid having to have another escape method for javascript reserved keywords, ie {for:"foo"}.
You are correct to use strings as the key. Here is an excerpt from RFC 4627 - The application/json Media Type for JavaScript Object Notation (JSON)
2.2. Objects
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
[...]
2.5. Strings
The representation of strings is similar to conventions used in the C
family of programming languages. A string begins and ends with
quotation marks. [...]
string = quotation-mark *char quotation-mark
quotation-mark = %x22 ; "
Read the whole RFC here.
From 2.2. Objects
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.
and from 2.5. Strings
A string begins and ends with quotation marks.
So I would say that according to the standard: yes, you should always quote the key (although some parsers may be more forgiving)
Yes, quotes are mandatory. http://json.org/ says:
string
""
" chars "
Not if you use JSON5
For regular JSON, yes keys must be quoted. But if you need otherwise, checkout widely used JSON5, which is so-named because is a superset of JSON that allows ES5 syntax, including:
unquoted property keys
single-quoted, escaped and multi-line strings
alternate number formats
comments
extra whitespace
The JSON5 reference implementation (json5 npm package) provides a JSON5 object that has parse and stringify methods with the same args and semantics as the built-in JSON object.
widely used, and depended on by many high profile projects
JSON5 was started in 2012, and as of 2022, now gets >65M downloads/week, ranks in the top 0.1% of the most depended-upon packages on npm, and has been adopted by major projects like Chromium, Next.js, Babel, Retool, WebStorm, and more. It's also natively supported on Apple platforms like MacOS and iOS.
~ json5.org homepage
In your situation, both of them are valid, meaning that both of them will work.
However, you still should use the one with quotation marks in the key names because it is more conventional, which leads to more simplicity and ability to have key names with white spaces etc.
Therefore, use the one with the quotation marks.
edit// check this: What is the difference between JSON and Object Literal Notation?
Since you can put "parent.child" dotted notation and you don't have to put parent["child"] which is also valid and useful, I'd say both ways is technically acceptable. The parsers all should do both ways just fine. If your parser does not need quotes on keys then it's probably better not to put them (saves space). It makes sense to call them strings because that is what they are, and since the square brackets gives you the ability to use values for keys essentially it makes perfect sense not to.
In Json you can put...
>var keyName = "someKey";
>var obj = {[keyName]:"someValue"};
>obj
Object {someKey: "someValue"}
just fine without issues, if you need a value for a key and none quoted won't work, so if it doesn't, you can't, so you won't so "you don't need quotes on keys". Even if it's right to say they are technically strings. Logic and usage argue otherwise. Nor does it officially output Object {"someKey": "someValue"} for obj in our example run from the console of any browser.