Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON formatter lib

Tags:

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?

like image 974
iain Avatar asked Nov 04 '11 10:11

iain


2 Answers

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.

like image 74
phihag Avatar answered Oct 21 '22 16:10

phihag


JSONLint includes that functionality

like image 41
Quentin Avatar answered Oct 21 '22 15:10

Quentin