how to format Json output?

16,262

Solution 1

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

Solution 2

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();
}
Share:
16,262
001
Author by

001

Only questions with complete answers are accepted as solutions.

Updated on July 28, 2022

Comments

  • 001
    001 almost 2 years

    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?

  • Diganta Kumar
    Diganta Kumar over 11 years
    Fiddler from Telerik format the JSON response nicely.
  • RomanKousta
    RomanKousta about 10 years
    Why should I be careful about formatting sensitive data?
  • Jon Skeet
    Jon Skeet about 10 years
    @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?
  • RomanKousta
    RomanKousta about 10 years
    @JonSkeet: Makes perfect sense.
  • Nitin Sawant
    Nitin Sawant almost 10 years
    OP wants it to be done programatically using C#