Reputation: 2625
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
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
Reputation: 108040
var obj = JSON.parse('{"apple":30,"orange":50}');
// obj.apple === 30
Upvotes: 0