Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting json documents

. I am building an utility to manage mongo database. I am using visual studio 2010 and framework 4.0. Now, when display documents , they are not formatted thus not understandable. I just want to beautify it with indentations and line breaks without serializing it; since I am not working with objects. I just got document and I want to format them. For this , I have tried JsonPrettyPrinter.dll but it uses framework 3.5. I have json.net but I dont know how to use it for formatting. Please tell me the way of doing it.

like image 321
Himani Talesara Avatar asked May 14 '12 12:05

Himani Talesara


People also ask

How should JSON files be formatted?

JSON File StructureJSON data is written in key/value pairs. The key and value are separated by a colon(:) in the middle with the key on the left and the value on the right. Different key/value pairs are separated by a comma(,). The key is a string surrounded by double quotation marks for example “name”.

How does a JSON file look like?

A JSON object is a key-value data format that is typically rendered in curly braces. When you're working with JSON, you'll likely come across JSON objects in a . json file, but they can also exist as a JSON object or string within the context of a program.

How do I make a JSON file readable?

If you need to convert a file containing Json text to a readable format, you need to convert that to an Object and implement toString() method(assuming converting to Java object) to print or write to another file in a much readabe format. You can use any Json API for this, for example Jackson JSON API.

How are JSON files structured?

JSON has the following syntax. Objects are enclosed in braces ( {} ), their name-value pairs are separated by a comma ( , ), and the name and value in a pair are separated by a colon ( : ). Names in an object are strings, whereas values may be of any of the seven value types, including another object or an array.


1 Answers

If you're using JSON.NET, you can use this code to format (pretty-print) the JSON document:

string json = "...";
JToken jt = JToken.Parse(json);
string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
like image 60
carlosfigueira Avatar answered Sep 24 '22 09:09

carlosfigueira