javascript - Can use this as a json object? Custom string to json parser -
i'm making little parser makes json objects out of easier input strings. have 2 input fields you'll see , use first table name, next data page. i'm starting extremely simple know won't work complex examples. that'll come later. see i'm missing {} i'll add later. little parser spits out:
{pizzas:[ size:"large";toppings:"sausage"; ] } but i'm curious, technically working json object right? var "object" mean.
here's el code!
<!doctype html> <html> <head> </head> <body> input like:<br/> table: pizzas<br/> data: size:"large";toppings:"sausage";<br/> <form name="form1" onsubmit="getstring(); return false;"> table name<input type="text" name="tablejob" id="tablejob" value='example: pizzas'><br/> data<input type="text" name="datajob" id="datajob" value='example: size:"large"; toppings:"sausage";'> <input type="submit" value="submit"> </form> <p id="myjson"></p> <script> var w, x, y, z; function getstring(){ x = document.getelementbyid("tablejob").value; //get table user y = document.getelementbyid("datajob").value; //get data user var object = '<p>{' + x + ':[<br/>' + '  ' + y + ' ]<br/>' + '}'; document.getelementbyid("myjson").innerhtml = object; } //now add object our json page </script> </body> //////////////////////////////////////////////////////////////////////////////// correct way now:
<body> input like:<br/> table: "pizzas"<br/> data: "size":"large","toppings":"sausage",<br/> <form name="form1" onsubmit="getstring(); return false;"> table name<input type="text" name="tablejob" id="tablejob" value='"pizzas"'><br/> data<input type="text" name="datajob" id="datajob" value='"size":"large", "toppings":"sausage,"'> <input type="submit" value="submit"> </form> <p id="myjson"></p> <script> var w, x, y, z; function getstring(){ x = document.getelementbyid("tablejob").value; //get table user y = document.getelementbyid("datajob").value; //get data user var obj = '<p>{ ' + x + ' : [<br/>' + '  {' + y + '} ]<br/>' + '}'; document.getelementbyid("myjson").innerhtml = obj; var myjsonstring = '{' + x + ':[' + '{' + y + '} ]' + '}'; alert(myjsonstring); } </script> </body>
the first object have neither valid json object nor valid javascript object literal.
a proper javascript object literal should this:
var pizzas = { pizzas:[ {size:"large",toppings:"sausage"} ], //notice enclosing curlys around size , toppings. } secondly, object you're getting var object... this
"<p>{pizzas:[<br/>  size:"large";toppings:"sausage" ]<br/>}" which unstripped definately not object, stripping html out:
"{pizzas:[size:"large";toppings:"sausage"]}" still won't produce valid json object , working json.stringify() won't either because array can't hold key-value pairs you're trying insert.
wrapping these in object literal fix it, see above, remove semi-colon appears in array.
Comments
Post a Comment