JSON formatter lib

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?

Answers:

Answer

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.

Answer

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

Hope this will help some one..

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.