28

Possible Duplicate:
JSON pretty print using JavaScript

I'd like to display my raw JSON data on a HTML page just as JSONview does. For example, my raw json data is:

  {
   "hey":"guy",
   "anumber":243,
   "anobject":{
      "whoa":"nuts",
      "anarray":[
         1,
         2,
         "thr<h1>ee"
      ],
      "more":"stuff"
   },
   "awesome":true,
   "bogus":false,
   "meaning":null,
   "japanese":"明日がある。",
   "link":"http://jsonview.com",
   "notLink":"http://jsonview.com is great"
}

It comes from http://jsonview.com/, and what I want to achieve is like http://jsonview.com/example.json if you use Chrome and have installed the JSONView plugin.

I've tried but failed to understand how it works. I'd like to use a JS script (CSS to highlight) to custom format my raw JSON data which is retrieved by ajax and finally put it on a HTML page in any position like into a div element. Are there any existing JS libraries that can achieve this? Or how to do it?

Community
  • 1
  • 1
timon.ma
  • 319
  • 1
  • 4
  • 10

3 Answers3

39

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

guypursey
  • 3,114
  • 3
  • 24
  • 42
  • 1
    This question apparently closed while I was posting my answer. I will leave my answer here in case it is of any use to anyone but the code given in answer to the [identified question to which this one's a possible duplicate](http://stackoverflow.com/questions/4810841/json-pretty-print-using-javascript) is a bit more magic than mine :-) – guypursey Jan 07 '13 at 14:43
  • Thank you a lot!!I'd like to try your method.My HTML page has add jquery library,I wonder if there exists some other library based on jquery so that I can achieve my goal.I want easily coding...Mainly because I'm not good at javascript -.- I'll Try! – timon.ma Jan 07 '13 at 15:20
  • This is so long solution. Means a bit complex. I found a tricky solution by which i can display json data in better format. here is your solution :http://www.codematrics.com/how-to-display-json-data-in-format/ – Miral Viroja May 10 '15 at 06:13
  • 1
    Ok, so using regex for formatting is absolutely terrible. Regex doesn't handle nesting or embedding (e.g. in strings inside the JSON) well etc. Just use `JSON.stringify(data, null, 2)` which will indent the string _for you_. `div.innerHtml = '
    ' + JSON.stringify(data, null, 2) + '
    ';` No need for all that code.
    – DDS May 19 '19 at 19:35
9

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

Rui Vieira
  • 5,253
  • 5
  • 42
  • 55
  • I'm sorry but English is not my mother tongue.What I want is 2.The real instance acts like that: I acqurire data through,and then put into an HTML page,in a DIV element.Raw data is unreadable,so I want to format it like JSONView does,but JSONView only format the data which is only json data gotten from server and contains none html element. – timon.ma Jan 07 '13 at 14:59
  • for hightlight.js, I have tried it,but it seems doesn't work.The json data displays only in one line,and I don't know why.I checked the source file , it seems that the row json data has been written in
    ...e,I can't get more documentation from http://softwaremaniacs.org/soft/highlight/en/description/ .....
    – timon.ma Jan 07 '13 at 15:03
  • Hi timon.ma. In that case I suggest you look at the link on top of this page: http://stackoverflow.com/questions/4810841/json-pretty-print-using-javascript. It includes a simple snippet to "pretty print" your JSON. – Rui Vieira Jan 07 '13 at 15:44
  • thanks,i've just now learned that JSON.stringify(param1, param2,param3),the third helps me solve the problem.Another question is in my json data displayed,there exists some mark like \n,in fact I want it to print an enter,em,how can I do it? – timon.ma Jan 07 '13 at 16:14
0

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

Community
  • 1
  • 1
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188