20

I'm looking for a way to format (as in whitespace, newlines where suitable) a JSON result so that I can display the actual result but well formatted.

$.ajax({
                url: "/Home/Send",
                type: "POST",
                data: JSON.stringify(request),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#ResponseBody").val(data.ResponseBody);
                },
                error: function (data) {
                    alert(data);
                }
            });

this is my code, which works fine data.ResponseBody contains the JSON, but as expected, it is not well formatted.

Does anyone know of a jQuery plugin / method that would allow me to format the response?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
iain
  • 1,693
  • 13
  • 19

3 Answers3

41

You can simply use the third parameter of JSON.stringify:

    success: function (data) {
        var obj = JSON.parse(data.ResponseBody);
        $("#ResponseBody").val(JSON.stringify(obj, null, 4));
    },

Don't forget to add a CSS rule like #ResponseBody {white-space: pre;} to make newlines display.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

JSONLint includes that functionality

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

I found a very simple code to format JSON.. http://joncom.be/code/javascript-json-formatter/

Hope this will help some one..

Dilip Rajkumar
  • 7,006
  • 6
  • 60
  • 76