How to display raw JSON data on a HTML page

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?


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.


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:

  • You want to show the raw JSON (not an HTML page), as in your example
  • 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.


    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.

    链接地址: http://www.djcxy.com/p/8442.html

    上一篇: 在网页上即时打印JSON文本?

    下一篇: 如何在HTML页面上显示原始JSON数据