javascript - Json pretty function is not working -


im new javascript , have print json output using pretty function, output not expected, prints normal im expecting indentation. have gone through following links, can please me why not working.

how can pretty-print json using javascript?

<html> <script type="text/javascript">     function showjson(){             var jsonstring = "{array:[1,2,3],boolean:true,null:null,number:123,object:{a:b,c:d,e:f},string:hello world}";         document.getelementbyid('json_output').innerhtml = json.stringify(jsonstring, null, '\t');     }      function output(inp) {         document.body.appendchild(document.createelement('pre')).innerhtml = inp;     }   </script> <body>     <input type="button" onclick="showjson();" value="click me!!">     <br>     <br>     string device : <div id='json_output'>hi</div> </body> 

you taking invalid json text input json.stringify. if want stringify javascript object json text need to:

  1. fix errors in json text
  2. convert json text have javascript object (with json.parse).

you appending generated data <div> (the pre mentioned in output function isn't used never call function), , have no css in example cause white space significant, need change that.

using innerhtml isn't safe, general case, either. json might contain & or < characters should use createtextnode make sure such character suitably escaped.

<!doctype html>  <html> <script type="text/javascript">     function showjson(){           var jsonstring = '{"array":[1,2,3],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"hello world"}';         var obj = json.parse(jsonstring);         document.getelementbyid('json_output').innerhtml = "";         document.getelementbyid('json_output').appendchild(document.createtextnode(json.stringify(obj, null, '\t')));     } </script> <body>   <input type="button" onclick="showjson();" value="click me!!">   <p>string device:</p>   <pre id='json_output'>hi</pre> </body> 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -