8

I already read this topic How can I pretty-print JSON using JavaScript?

anyway the correct answer just works if I want to print that json to the console.

Doing something like

$("#myDiv").text(parsedJson);

or

$("#myDiv").html(parsedJson);

will not result in a pretty json.

My intention is to display a dialog box containing that json object, in an human readable form..is it possible?

Community
  • 1
  • 1
Phate
  • 6,066
  • 15
  • 73
  • 138
  • 3
    Whomever voted to close this as "too broad": How in the world is this question "too broad"? It's very specific, has a clear focus, and clarifying code as to what was tried and what is being attempted. – Brad Jun 16 '14 at 13:54
  • https://stackoverflow.com/questions/4810841/pretty-print-json-using-javascript?rq=1 – pankaj Feb 02 '21 at 13:18

2 Answers2

15

Untested, but should get you started:

$('#myDiv').append(
    $('<pre>').text(
        JSON.stringify(parsedJson, null, '  ')
    )
);
Brad
  • 159,648
  • 54
  • 349
  • 530
  • it's work perfectly with JSON object. When i try with XML object then it will not work so do you have solution for XML object ? – Hiren Tailor Apr 06 '17 at 04:19
  • @HirenTailor Imagine that... an answer about serializing an object as JSON outputs JSON. You should post a separate question with whatever it is that you're trying to do. This question is totally unrelated. – Brad Apr 06 '17 at 04:38
  • yes i know @brad and i thought may be you have some idea about it so that's why i ask you in comment. – Hiren Tailor Apr 06 '17 at 04:41
  • @HirenTailor StackOverflow works different than other sites. Separate questions should be posted as separate questions, rather than taking existing questions and answers off-topic. – Brad Apr 06 '17 at 04:42
6

You could use <pre> tag instead of div, assuming parsedJson contains all newlines and indentation.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66