How to convert a string into a object How to convert a string into a object json json

How to convert a string into a object


You can solve this by many methods but I prefer to use a library like the JSON library from Mr. Douglas Crockford.

If you use the library it is as simple as

var object = JSON.parse('{"apple":30,"orange":50}')alert(object.apple) // will alert 30

The most dangerous and ugly way is to use the eval() function.

eval('object={"apple":30,"orange":50}')alert(object.apple) // will alert 30

Never use this.

The json.org site has references to more json libraries in different languages. Javascript specific information can be found here.


Use Crockford's JSON parser

var obj = JSON.parse('{"apple":30,"orange":50}');// obj.apple === 30