user2110167
user2110167

Reputation: 249

Query regarding Difference between JavaScript Object And JSOn Object

Here is my question: in java script: we hav an object:

var someObject={"name":"somename"};

Now we want to get the name ,we ll do

alert(someObject.name); //it will print somename Right?

Same object i get from a source which sends a JSON object as

someJSONObject={"name":"someName"};

Now in my javascript code ,without parsing this someJSONObject ,i can get name as

alert(someJSONObject.name);

If it is so ,why we need to convert JSON Object to a javaScript Object by parsing it ,when we can use it as an object without parsing or using eval()?

Thanks !

Upvotes: -1

Views: 93

Answers (2)

Evan Davis
Evan Davis

Reputation: 36592

JSON is a string, so it's something like var jsonObject = '{"name":"someName"}'; an object is an object.

Upvotes: 1

Esailija
Esailija

Reputation: 140210

Because it's not a JSON Object. The syntax {"name":"someName"}, with quoted keys, does not make it JSON, the same syntax is supported by Javascript object literals.

JSON can be embedded in Javascript strings. Like:

var json = '{"key": "value"}';

Then you can parse it into Javascript data types:

var obj = JSON.parse( json );

Note that eval may cause syntax errors because the syntaxes of JSON and Javascript are not ultimately compatible. The above would have caused a syntax error if evaled.

Upvotes: 1

Related Questions