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?

4
  • 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. Commented Nov 24, 2011 at 7:05
  • Do you need this for debugging? Im just interested Commented Nov 24, 2011 at 7: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). Commented Nov 24, 2011 at 7:11
  • 1
    @Jon, its good when you want to debug :) thanks. Commented Nov 24, 2011 at 9:25

3 Answers 3

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.)

Sign up to request clarification or add additional context in comments.

4 Comments

Fiddler from Telerik format the JSON response nicely.
Why should I be careful about formatting sensitive data?
@ZinanXing: Look at the context of the sentence: online JSON formatters. If you've got private information about your customers, how do you think they'd feel about you submitting them (probably over HTTP) to some 3rd party website for formatting?
@JonSkeet: Makes perfect sense.
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();
}

Comments

-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

1 Comment

OP wants it to be done programatically using C#

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.