Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  182] [ 2]  / answers: 1 / hits: 78168  / 14 Years ago, wed, october 20, 2010, 12:00:00

I am new to JSON and JavaScript objects.




  • Can someone please explain the differences between JSON and JavaScript object?

  • What are their uses?

  • Is one better than the other? Or does it depend on the situation?

  • When to use which one, in what situation?

  • Why was JSON created in the first place? What was its main purpose?

  • Can someone give examples of when one should use JSON rather than a JavaScript object and vice versa?


More From » json

 Answers
15

First you should know what JSON is:




  • It is language agnostic data-interchange format.



The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.



For example, in JSON all keys must be quoted, while in object literals this is not necessary:



// JSON:
{ foo: bar }

// Object literal:
var o = { foo: bar };


The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:



var o = { if: foo }; // SyntaxError in ES3


While, using a string literal as a property name (quoting the property name) gives no problems:



var o = { if: foo }; 


So for compatibility (and easy eval'ing maybe?) the quotes are mandatory.



The data types in JSON are also restricted to the following values:




  • string

  • number

  • object

  • array

  • A literal as:


    • true

    • false

    • null




The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.



// Invalid JSON:
{ foo: 'bar' }


The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.



// Invalid JSON:
{ foo: 0xFF }


There are some buggy implementations (Firefox 3.5+, IE8+, json2.js) where octal literals are wrongly allowed, e.g. JSON.parse('01') should produce a SyntaxError.


[#95249] Monday, October 18, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jameson

Total Points: 534
Total Questions: 103
Total Answers: 102

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
jameson questions
;