0

I have JavaScript code below.

var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]";

I need convert the string to an data by delete the "" surrounding the array stored as "data" in JavaScript so after convert it suppose like below:

var data = [{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}];

How to make the convert?

4
  • 1
    The first line is not a valid JS litteral string ... it would need mixed "/' quotes Commented Jun 23, 2015 at 13:48
  • you might be looking for eval(). something like data = eval(data); Commented Jun 23, 2015 at 13:48
  • The first line is not valid JS syntax, so you can't use JS to convert what's in data because the code won't even run. You'd need to fix the server-side code to return something valid. Commented Jun 23, 2015 at 13:52
  • Well then please update your question to show that properly. The first line of code shown is not valid JS. Commented Jun 23, 2015 at 13:55

1 Answer 1

3

To convert a JSON object to Javascript object use:

var data = '[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]';
JSON.parse(data);

But first change the double quote to single quote, otherwise the JSON object wont be a valid JSON.

After this you can walk the array in the following way:

var jsonParsed = JSON.parse(data);

for(var val in jsonParsed) {
   if(jsonParsed.hasOwnProperty(val)) {
      // do something with the values
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I need using mustache to populate it. like var rendered = Mustache.render(template, data); even i pass in JSON.parse(data); as the data, it still not work, untill I delete the "" surrounding the array stored as "data" in JavaScript. but how to remove "" ?
But why you are not sending in the correct format from backend?
You need to resolve the issue before you send to javascript, otherwise JS will throw you an error

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.