user556673
user556673

Reputation: 2625

How to convert a string into a object

I've a string value in the format '{"apple":30,"orange":50}'. How can I convert it into a javascript object of format

{apple: 30, orange: 50}

So that I can get the value for apple by using object.apple.

Upvotes: 2

Views: 279

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388436

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.

Upvotes: 7

Andreas Grech
Andreas Grech

Reputation: 108040

Use Crockford's JSON parser

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

Upvotes: 0

Related Questions