8

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?

Community
  • 1
  • 1
001
  • 62,807
  • 94
  • 230
  • 350
  • 1
    You say it "should" look like that - why? It's nice to be *able* to format it, but it's important to understand that the two versions are equivalent as far as the JavaScript consuming the data is concerned. – Jon Skeet Nov 24 '11 at 07:05
  • Do you need this for debugging? Im just interested – Grrbrr404 Nov 24 '11 at 07:06
  • In addition to @JonSkeet - formating you JSON nicelly will add just a bit more of overhead (because the whitespace characters will need to be transfered through the wire as well). – Pavel Donchev Nov 24 '11 at 07:11
  • 1
    @Jon, its good when you want to debug :) thanks. – 001 Nov 24 '11 at 09:25

3 Answers3

23

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 Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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();
}
bornfromanegg
  • 2,826
  • 5
  • 24
  • 40
-1

If you call your service from Firefox there's this nice plugin that will prettify the JSON for you: JSONView

I also used to use this website to format and validate any JSON: JSON Formatter

CyberDude
  • 8,541
  • 5
  • 29
  • 47