I am retrieving a string in json format from a php file and assigning it to a var in javascript

string = {"name": "piet", "id": "45"}

how do i convert this string into a real json object?

Recommended Answers

All 3 Replies

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);

jQuery's 'parseJSON()' has the advantage of not using 'eval()' for those browsers that support a 'parseJSON()' function. Of course, that excludes you know who, so this isn't yet a big advantage.

It is safe to 'eval()' JSON if your code creates the string to 'eval()'. It's an invitation to hackers if you 'eval()' stuff the user types into a textbox, for example. Crockford has a nearly bulletproof JSON parser online if you need security.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.