简体   繁体   中英

javascript convert string to data

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?

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM