JSON.stringify output to div in pretty print way

后端 未结 12 2325
野趣味
野趣味 2020-11-29 18:17

I JSON.stringify a json object by

result = JSON.stringify(message, my_json, 2)

The 2 in the argument above is su

相关标签:
12条回答
  • 2020-11-29 18:33

    Consider your REST API returns:

    {"Intent":{"Command":"search","SubIntent":null}}
    

    Then you can do the following to print it in a nice format:

    <pre id="ciResponseText">Output will de displayed here.</pre>   
    
    var ciResponseText = document.getElementById('ciResponseText');
    var obj = JSON.parse(http.response);
    ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);   
    
    0 讨论(0)
  • 2020-11-29 18:38

    My proposal is based on:

    • replace each '\n' (newline) with a <br>
    • replace each space with &nbsp;

    var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };
    
    
    document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)
         .replace(/\n( *)/g, function (match, p1) {
             return '<br>' + '&nbsp;'.repeat(p1.length);
         });
    <div id="newquote"></div>

    0 讨论(0)
  • 2020-11-29 18:44

    Make sure the JSON output is in a <pre> tag.

    0 讨论(0)
  • 2020-11-29 18:44

    use style white-space: pre the <pre> tag also modifies the text format which may be undesirable.

    0 讨论(0)
  • 2020-11-29 18:45

    If this is really for a user, better than just outputting text, you can use a library like this one https://github.com/padolsey/prettyprint.js to output it as an HTML table.

    0 讨论(0)
  • 2020-11-29 18:46

    A lot of people create very strange responses to these questions that make alot more work than necessary.

    The easiest way to do this consists of the following

    1. Parse JSON String using JSON.parse(value)
    2. Stringify Parsed string into a nice format - JSON.stringify(input,undefined,2)
    3. Set output to the value of step 2.

    In actual code, an example will be (combining all steps together):

        var input = document.getElementById("input").value;
        document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);
    

    output.value is going to be the area where you will want to display a beautified JSON.

    0 讨论(0)
提交回复
热议问题