In order to convert very long string which is separated by common (,) to a JavaScript object and then use these data shown in the web page, we should do, 1. Split the string into an array 2. Create a JavaScript string containing JSON syntax 3. For securer method, use JSON parser JSON.parse() instead of Javascript eval() function to parse the JSON text and produce a JavaScript object
Given String: Apple,89,Banana,39,Grape,58,Cheery,33
Printout: how many bananas in the supermarket
Click the button to display the object values after the split and conversion.
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to display the object values after the split and conversion.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var str="Apple,89,Banana,39,Grape,58,Cheery,33"; var n=str.split(","); var txt =""; for(var i=0; i<n.length; i++) { txt += '{"Name":"'+ n[i]+'","Num":"' + n[i+1] + '"}'; if(i!= n.length-2) txt += ','; i++;} txt = '{"fruit" : [' + txt + ']}'; //var obj = eval("(" + txt + ")"); obj2 = JSON.parse(txt); document.getElementById("demo").innerHTML="There are " + obj2.fruit[1].Num + " " + obj2.fruit[1].Name + " in the supermarket."; } </script> </body> </html>
No comments:
Post a Comment