My web service responses has mimetype: "application/json" and my JSON outputs without spacing, like this
{"Data":{"Item":"123","Timestamp":"2011-11-24T17:50:43"}}
When the JSON should output like this
{
"Data":{
"Item":"123",
"Timestamp":"2011-11-24T17:50:43"
}
}
Is there any way I can fix the JSON format, so it appears like #2?
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.
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.
I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this.
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.)
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With