How to display raw JSON data on a HTML page

231,773

Solution 1

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.

Solution 2

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.

Share:
231,773

Related videos on Youtube

timon.ma
Author by

timon.ma

Updated on July 09, 2022

Comments

  • timon.ma
    timon.ma almost 2 years

    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?

    • Arvind Bhardwaj
      Arvind Bhardwaj over 11 years
      Try a syntax highlighter plugin.
    • FullStack
      FullStack almost 9 years
      Example of JSON pretty printing to <pre> block - jsfiddle.net/K83cK
    • Nguyen Tran
      Nguyen Tran almost 8 years
      You should try <pre> block. It's simple and work fine.
  • guypursey
    guypursey over 11 years
    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 is a bit more magic than mine :-)
  • timon.ma
    timon.ma over 11 years
    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
    timon.ma over 11 years
    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 <pre></pre>...e,I can't get more documentation from softwaremaniacs.org/soft/highlight/en/description .....
  • timon.ma
    timon.ma over 11 years
    maybe you are right,my expression has something wrong ..
  • timon.ma
    timon.ma over 11 years
    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!
  • knight
    knight over 11 years
    Hi timon.ma. In that case I suggest you look at the link on top of this page: stackoverflow.com/questions/4810841/…. It includes a simple snippet to "pretty print" your JSON.
  • timon.ma
    timon.ma over 11 years
    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?
  • Miral Viroja
    Miral Viroja about 9 years
    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 :codematrics.com/how-to-display-json-data-in-format
  • Miral Viroja
    Miral Viroja about 9 years
  • DDS
    DDS almost 5 years
    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 = '<pre>' + JSON.stringify(data, null, 2) + '</pre>'; No need for all that code.