In this post we will discuss how we can format or style the JSON you get from the server. Sometimes you may need to show the exact JSON you get from your API or from server in your web page. Normally if you just bind this JSON to any pre tag, it will look like just a straight line. Isn’t it? To overcome this we have an option in jQuery . I hope you will like this.
For the past few months I am working with some Web API projects. As you all know the preferred output of an API is JSON, I am returning JSON from my API. I wanted to show this JSON in a Pre tag as a result, but in a formatted way or stylish way. Here I am going to explain how we can do this.
Using the code
Before getting started, please make sure that you have added the jQuery reference to your page.
Now let us say we are getting a JSON as follows from our API.
It will obviously looks like preceding when you just append it to a pre tag.
Now we will format this JSON string with JQuery Parse and JQuery stringify method as follows.
var tmpData = JSON.parse(data);
var formattedData = JSON.stringify(tmpData, null, ‘\t’);
Here output is the id of our pre tag which we defined as follows.
Now if you bind the data after the formatting to pre tag, you will get an out put as follows.
Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.
Your turn. What do you think?
A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.