1

I'm a newbie to JS and JSON and trying to understand the difference, I see other threads on this difference but still have few unanswered questions,

I have created 3 objects

  1. Key-vaue pairs in double quotes
  2. Key without quotes but value with quotes
  3. Key-value pairs in single quotes.

Questions.

  1. Asis, is it safe to assume if all the 3 objects are Javascript objects?
  2. How do I determine which one is JSON Object here, when I print the objects in the log, all the objects looks same. Is there a way to determine the JSON Object?
  3. If JSON Objects - key-value pairs are enclosed in double quotes, what does the single quote mean?

Code:

<html>
    <head>
        <script>
            var jsobject = {"fname":"Bob","lname":"Mike"}
            console.log(jsobject)

            var jsobject = {fname:"Bob",lname:"Mike"}
            console.log(jsobject)

            var jsobject = {'fname':'Bob','lname':'Mike'}
            console.log(jsobject)

        </script>
    </head>
    <body>
    </body>
</html>
Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 1
    @susheel: There's a huge difference. They just happen to use an overlapping syntax. – cookie monster Dec 27 '13 at 18:37
  • 2
    1) Yes, all 3 are JavaScript objects. 2) To JavaScript, JSON is a String representation, which is why `JSON.stringify()` returns a `String` and `JSON.parse()` expects a `String`. 3) In JavaScript object literals/initializers, identifiers, numbers, and both single- and double-quoted strings can all be used as keys. JSON uses stricter syntax and only allows double-quoted strings. – Jonathan Lonowski Dec 27 '13 at 18:37
  • 1
    you don't have any JSON in your code, just three different yet equivalent object literal formats. only static code analysis could spot the difference. JSON uses JSON.parse/eval to go live, i don't see anything like that here... – dandavis Dec 27 '13 at 18:38
  • In your examples, the first Object is also a valid JSON string. The second and third example are valid Objects, but are invalid JSON strings because the keys and values are not wrapped in double quotes. – Cody Bonney Dec 27 '13 at 18:38
  • can someone answer in a clear way..Its all confusing here. with some example – Susheel Singh Dec 27 '13 at 18:40
  • @CodyBonney The important difference is that the first object would be a valid JSON string if wrapped in quotation marks. Or, in other words, its JSON representation would be identical to the object notation used to create it. – JJJ Dec 27 '13 at 18:41
  • x=5; x=+'5'; x=0x5; all are the same, even if one happens to look like something else. – dandavis Dec 27 '13 at 18:42
  • @Juhana: if you wrapped quotes around the first one, it would be a syntax error, not JSON. – dandavis Dec 27 '13 at 18:43
  • @dandavis Single quotes. – JJJ Dec 27 '13 at 18:43
  • @susheel what didn't you understand? It is pretty much impossible to explain it better than Jonathan's comment. – Fabrício Matté Dec 27 '13 at 18:44
  • i found it here http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/ – Susheel Singh Dec 27 '13 at 18:46
  • As you might know, JSON stands for `JavaScript Object Notation` and it is already a JavaScript Object. there is no difference, but in terms of double quotes and single quotes, from Javascript aspect of it there is no difference but if you want to `send` it as a querystring you' better use double quotes, because js encodeURI() and encodeURIComponent dont escape single quotes – Mehran Hatami Dec 27 '13 at 18:46
  • @Juhana thanks for bringing that up. I should have worded my comment a little better. – Cody Bonney Dec 27 '13 at 18:49
  • 2
    susheel: yeah, that's a good read. @MehranHatami what do you mean by "there is no difference"? JSON is serialized data in string form, that's completely different from JS objects. – Fabrício Matté Dec 27 '13 at 18:49
  • and you can also don't use quotes for your keys, but if your key doesn't meet JavaScript variables naming conventions, for instance if your key is a reserved key word in js, you have to use quotes. – Mehran Hatami Dec 27 '13 at 18:50
  • @Fabrício Matté : as I said before JSON stands for `JavaScript Object Notation`, and the idea of using JSON as a protocol to send and receive data, not only has originated from js objects, but also they are the same. for years, before someone came up with this idea, we've been using JSON in js. make sense? – Mehran Hatami Dec 27 '13 at 18:53
  • 1
    @MehranHatami No. The notation is *similar* - sure it was based in the JS objects notation, **however** the term "JSON" refers to a specification which defines a much stricter subset of the JS object notation. JSON is used as a data interchange language and can only occur in string context. I'd suggest reading up the link susheel sent, it's very enlightening: [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Fabrício Matté Dec 27 '13 at 18:59
  • @Fabrício Matté :'JSON is used as a data interchange language', that's right and I read that link, for those who has started using JSON with a server-side perspective, it won't make sense. I still insist on this, The notation is not just similar, it is the exact same thing. – Mehran Hatami Dec 27 '13 at 19:11
  • @MehranHatami I don't want to extend this too much further but, they are not "exact the same thing". For example: `{ unquotedProp: 42 }` is a valid JS object but not valid JSON (**all** JSON strings must be quoted), `{"fun": function(){} }` is valid a JS object but not valid JSON (JSON does not define a "function" type) etc. JSON is a stricter subset of JS object notation, that means any JSON string could be used as an object literal, but not the other way around. – Fabrício Matté Dec 27 '13 at 19:15
  • Also I'm not sure what do you mean by "for those who has started using JSON with a server-side perspective, it won't make sense". Let's assume a PHP back-end which outputs a JSON response to an Ajax call: `echo json_encode(array('hello'=>'world'));` - it is clear that the back-end is outputting a string, and the receiving end will have to parse it (with `JSON.parse()`, unless you are using `jQuery.ajax()` which automatically parses a JSON response into an object before passing it to the callback). – Fabrício Matté Dec 27 '13 at 19:25
  • @Fabrício Matté: consider the other way round, `{ "unquotedProp": "42" }`, is a valid JSON object and all the JSON objects are always valid JS objects, quotes are there to make sure to prevent js engines from exceptions. BTW I really enjoyed this short discussion, lets move over. – Mehran Hatami Dec 27 '13 at 19:26
  • @MehranHatami same here. `=]` Just remember that to check if something is valid JSON, you should enclose it in a string and pass it to `JSON.parse()`, or better yet, paste it at http://jsonlint.com/ – Fabrício Matté Dec 27 '13 at 19:27
  • @Fabrício Matté: when I said "for those who has started using JSON ...", I meant as an old raw javascript developer I have been using JSON, far before than it became `a data interchange language`, and for those who haven't done that, it is not plausible. I think, that's too much, lets finish it. – Mehran Hatami Dec 27 '13 at 19:33
  • Sounds fair enough, I have a similar background as yours and I can agree there, though now I wonder - assuming someone who does not have experience with JS, maybe s/he wouldn't confuse JSON with literal objects? I mean, wouldn't it just look like plain serialized data? Ok that's enough. `:P` – Fabrício Matté Dec 27 '13 at 19:40

1 Answers1

4

I think you're confusing syntax and data.

Any number of technologies can have very similar syntax, yet that similar syntax may be used for entirely different purposes, and for creating vastly different data.

when we talk about JSON, we're talking about textual data with a Unicode encoding that follows a character syntax that is meant to be used as a data transferral mechanism. That JSON data can be transferred into a wide variety of different programming environments, parsed, and then converted into actual object structures that make sense for the environment.

The reason that it was named "JavaScript Object Notation" is that its notation is largely patterned after a subset of the literal syntax used in JavaScript programs to create objects and primitive values. Sadly, this naming contributes to the confusion of JavaScript developers.

So to determine if you're dealing with JSON, what's ultimately the most important thing to think about is whether what you're doing will result in the creation of Unicode data that follows the rules of JSON syntax.

Take this example:

var foo = {"bar":"baz"};

Is that JSON? Well if it runs in a JavaScript program, it will be evaluated, and foo will hold a reference to some memory that is not Unicode text data.

Sure we could isolate the {"bar":"baz"} part of the code, and transfer it into its own text file that is encoded as Unicode, but then we're really not dealing with the same example anymore.

So let's say we did that. We open our text editor, make sure it's set up for Unicode encoding, and then paste in that one part of the above code. So now the entirety of our text file is this:

{"bar":"baz"}

Now we can correctly say that we have JSON data. What if I added a ; to the end?

{"bar":"baz"};

It's no longer JSON because it has been corrupted by the ; which is not allowed. Again, we could play around with calling it JSON except for whatever isn't valid, but really it either is or isn't valid in its entirety.

So back to a JavaScript example. Does it every make sense to refer to JSON within the syntax of a JavaScript program? Well take our original example. If we could use some JavaScript syntax to create Unicode data and make it comply with JSON syntax, then yes, we could correctly speak of having JSON in our program.

So does JavaScript let us create Unicode data? Yes, all strings in JavaScript are UTF-16 encoded. Therefore all we need to do is create a string.

var foo = '{"bar":"baz"}';

Now we wouldn't call that entire line JSON, but we could correctly say that the foo variable refers to memory which does hold JSON data.

We could then transfer that data to a server written in an entirely different programming language, and as long as it has a JSON parser, it could parse it, and convert it to whatever object type makes sense to that server.

cookie monster
  • 10,671
  • 4
  • 31
  • 45