Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display raw JSON data on a HTML page [duplicate]

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?

like image 959
timon.ma Avatar asked Jan 07 '13 12:01

timon.ma


People also ask

How do I display formatted JSON data in HTML?

Use the JSON. stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way. Or Use <pre> tag for showing code itself in HTML page and with JSON.

How do I show JSON pretty?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

Which syntax is used for displaying JSON data on a view?

var jsonStr = JSON. stringify(jsonVar); And then you can insert into your HTML directly, for example: document.

How to display JSON data in a webpage?

We have the JSON data in data stored in a variable. Now we can use it to display the data in the webpage. 1. Display JSON Data As List To display the JSON data in a list we will create HTML elements dynamically and insert data in them. Before we start keep the data structure of JSON data in mind.

How to fetch JSON data in HTML using JavaScript?

Fetching the JSON data. To be able to display this data in our HTML file, we first need to fetch the data with JavaScript. We will fetch this data by using the fetch API. We use the fetch API in the following way: The url parameter used in the fetch function is where we get the JSON data. This is often an http address.

How to append JSON data dynamically to HTML elements?

First, we will fetch the JSON data by using the fetch API. This will return a promise with our JSON data. Then we will append the data dynamically by creating HTML elements on the fly. We will then append our JSON data to those elements. Getting JSON data from an API and display it on a web page is a common thing you will do quite often.

How to display JSON data in a Div when array is array?

How to display JSON data in a div when JSON data is in Array? Answer: You can use for it to loop thru the array and construct an HTML string. Use jQuery ‘s .append () to add the string to the body.


2 Answers

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.

like image 97
guypursey Avatar answered Sep 28 '22 02:09

guypursey


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.

like image 33
Rui Vieira Avatar answered Sep 28 '22 03:09

Rui Vieira