Jim Aho
Jim Aho

Reputation: 11887

Why are no curly brackets added to my JSON?

Why is the below code not outputting curly brackets around the value of json? I thought JSON is always encapsulated inside brackets.

var json = JsonConvert.SerializeObject("some text into json", Formatting.Indented);`

The resulting JSON is now "\"some text into json\"" rather than { "\"some text into json\"" }

Upvotes: 5

Views: 3252

Answers (2)

pabdulin
pabdulin

Reputation: 35229

The JSON stands for "JavaScript Object Notation" meaning that all data is represented as a single JavaScript object (a string that looks like a JavaScript code of the object, to be more correct).

That's why curly brackets are not mandatory, they are needed then necessary to represent complex object structure. { "some text into json" } (I omit quote escape for clariness) is just plain syntax error for JavaScript compiler! You can have { "key": "value", "other key": "other value" } objects, but a key without a value is error.

So the "some text into json" is the only possible correct JSON for the string object "some text into json".

Upvotes: 0

Spontifixus
Spontifixus

Reputation: 6660

This is because you simply serialized a string. Thus the serializer returns just the serialized string, which, in JSON, is just the string enclosed in quotes:

"some text"

JSON only adds curly braces if you serialize an object:

{
    "someStringProperty": "some text"
}

Also note that the backslashes in your output result from Visual Studio encapsulating the whole string in quotes again and also escapes quotes within the string. The "real" values of the serialized string just use simple quotes. Thus Visual Studio would display the above JSON string as follows:

"\"some text\""

or

"{ \"someStringProperty\": \"some text\" }"

Upvotes: 7

Related Questions