-1

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 !

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the reply .But when i can use JSONobject received from server in the same way as my normal javascript object,why we have to parse it and make it to a javascript object ?Why parsing is necessary if all the operations can be performed without it ?
@user2110167 Are you talking about embedding it inside <script> element? Then it is evaluated as Javascript code, and it might work depending on many factors.
i have a javascript function which receives a JSON object from Java code .If i don't parse that JSON object received and try to access the keys inside it ,i am able to do that .
@user2110167 If you are embedding JSON serialization inside Javascript context, then it will be evaluated as Javascript. Because of the 99.99% compatible syntax, it will work.
I was just confused between the two form of objects,because they look same too.Sorry for asking such a silly question.Thanks
|
1

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

3 Comments

Fine jsonObject is a string,then if i try to acces the name inside it ,i can simply do jsonObject.name .Why we need to parse it then ?
Well no, you can't access it via jsonObject.name. THat's the point
@Mchl You are right.i tried that and its a difference between the two .Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.