Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format Json output? [duplicate]

My web service responses has mimetype: "application/json" and my JSON outputs without spacing, like this

1

{"Data":{"Item":"123","Timestamp":"2011-11-24T17:50:43"}}

When the JSON should output like this

2

{
   "Data":{
      "Item":"123",
      "Timestamp":"2011-11-24T17:50:43"
   }
}

Is there any way I can fix the JSON format, so it appears like #2?

like image 429
001 Avatar asked Nov 24 '11 07:11

001


People also ask

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

How does JSON handle duplicate keys?

Parse the string using wither regex or tokens, add each key-value pair to a hashmap, and in the end recreate your JSON document with the duplicates removed. In this case though I would only remove key-value pairs that are exactly the same.

Can we have duplicate keys in JSON?

I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this.


2 Answers

I wouldn't change the format written out by the web service, but if you want to format it for diagnostic purposes you can use Json.NET to do this very simply:

JObject json = JObject.Parse(text);
string formatted = json.ToString();

The result is automatically formatted. You could put this into a small tool - either a desktop tool or a web page somewhere. (I wouldn't be surprised if there were already online JSON formatters, although obviously you'd want to be careful about formatting sensitive data.)

like image 189
Jon Skeet Avatar answered Oct 12 '22 07:10

Jon Skeet


Jon's answer doesn't seem to work if the root element of your json is an array. Using JToken instead of JObject fixed this for me. As an extension method on string, this looks like:

public static string FormatJson(this string json)
{
    return JToken.Parse(json).ToString();
}
like image 29
bornfromanegg Avatar answered Oct 12 '22 07:10

bornfromanegg