41

Using System.Text.Json i can pretty print json using serialization option.

var options = new JsonSerializerOptions{ WriteIndented = true };
jsonString = JsonSerializer.Serialize(typeToSerialize, options);

However, I have string JSON and don't know the concrete type. Ho do I pretty-print JSON string?

My old code was using Newtonsoft and I could do it without serialize/deserialize

public static string JsonPrettify(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return json;
    }

    using (var stringReader = new StringReader(json))
    using (var stringWriter = new StringWriter())
    {
        var jsonReader = new JsonTextReader(stringReader);
        var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
        jsonWriter.WriteToken(jsonReader);
        return stringWriter.ToString();
    }
}
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
LP13
  • 30,567
  • 53
  • 217
  • 400
  • There's no built-in API to copy from a `Utf8JsonReader` to a `Utf8JsonWriter` so parsing to `JsonDocument` and reserializing looks to be the way to go. See [How to pretty-print (format) System.Text.JsonElement to a string](https://stackoverflow.com/q/61598778/3744182). – dbc Jan 08 '21 at 01:14

3 Answers3

54

This works:

using System.Text.Json;
public static string JsonPrettify(this string json)
{
    using var jDoc = JsonDocument.Parse(json);
    return JsonSerializer.Serialize(jDoc, new JsonSerializerOptions { WriteIndented = true });
}
dlumpp
  • 891
  • 8
  • 14
0

This works :


    private static string PrettifyJson(string jsonString)
    {
        using (JsonDocument jsonDocument = JsonDocument.Parse(jsonString)){
            // Convert the JsonDocument back to a pretty-printed JSON string
            string prettifiedJson = 
            System.Text.Json.JsonSerializer.Serialize(jsonDocument.RootElement, new 
                JsonSerializerOptions
                {
                    WriteIndented = true
                });
            return prettifiedJson;
        }
    }

Igor Zelaya
  • 4,167
  • 4
  • 35
  • 52
0

You can acheive it with Newtonsoft.Json JToken class. Here is the code.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static string JsonPrettify(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return json;
    }
    return JToken.Parse(json).ToString(Formatting.Indented);
}