-1

Im new to Javascript and I have to print Json output using pretty function, but the output is not as expected, it just prints normal but Im expecting with indentation. I have also gone through the following links, can anyone please help me why this is not working.

How can I 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 FROM DEVICE : <div id='json_output'>HI</div>
</body>

Community
  • 1
  • 1
Pocoyo
  • 55
  • 1
  • 3
  • 8

2 Answers2

1

You are taking an invalid JSON text as input to JSON.stringify. If you want to stringify a JavaScript object into a JSON text then you need to:

  1. Fix the errors in the JSON text
  2. Convert the JSON text you have into a JavaScript object (with JSON.parse).

You are also appending the generated data to a <div> (the pre mentioned in the output function isn't used as you never call that function), and you have no CSS in the example that would cause white space to be significant, so you also need to change that.

Using innerHTML isn't safe, for the general case, either. The JSON might contain & or < characters so you should use createTextNode to make sure that any such character is 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 FROM DEVICE:</p>
  <pre id='json_output'>HI</pre>
</body>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You have thre problems :

  • you try to stringify a string, not an object, parse your JSON before : JSON.stringify(JSON.parse(jsonString), null, '\t');
  • your JSON is invalid, you need quotes around the field names and the string values
  • you put it in a div element where the formatting is lost. Use a PRE element instead : <pre id='json_output'>HI</pre>

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758