Runtime: Indenting and unindenting JSON should be easier

Created on 25 Sep 2019  路  3Comments  路  Source: dotnet/runtime

Imagine I need to unindent some raw JSON (for example, for error messages and logging). There is no simple way to do that; instead, I ended up writing the following, which seems a bit clunky:

```C#
public static string ChangeIndentation(string value, bool indented)
{
using (var stream = new MemoryStream())
{
var options = new JsonWriterOptions { Indented = indented };

    using (var writer = new Utf8JsonWriter(stream, options))
    {
        using var document = JsonDocument.Parse(value);
        document.WriteTo(writer);
    }

    stream.Position = 0;

    using (var reader = new StreamReader(stream))
        return reader.ReadToEnd();
}

}

### Proposal

```C#
namespace System.Text.Json
{
    partial class JsonDocument
    {
        public override string ToString() => ToString(indented: true);
        public string ToString(bool indented);
    }
}

Usage

C# public static string ChangeIndentation(string value, bool indented) { using var document = JsonDocument.Parse(value); return document.ToString(indented); }

api-suggestion area-System.Text.Json

Most helpful comment

The idea of seeing document.ToString(true) all over the place doesn't thrill me. How about changing the bool param to a JsonWriterOptions, then you'll end up with something like document.ToString(new JsonWriterOptions{ Indented=true }) which is longer but at least tells you what's going on more clearly. It'll also allow any future writer options to be set without adding to the api surface.

All 3 comments

The idea of seeing document.ToString(true) all over the place doesn't thrill me. How about changing the bool param to a JsonWriterOptions, then you'll end up with something like document.ToString(new JsonWriterOptions{ Indented=true }) which is longer but at least tells you what's going on more clearly. It'll also allow any future writer options to be set without adding to the api surface.

Not really sure how I feel about it, but it seems like ToString(string format) should be considered to keep consistency with everything else.

Have you tried the following?

public static string ChangeIndentation(string value)
{
    JsonNode node = JsonNode.Parse(value);
    return node.ToJsonString();
}

However I assume using the one you propose with JsonDocument would perform better since its read-only.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamesqo picture jamesqo  路  3Comments

bencz picture bencz  路  3Comments

noahfalk picture noahfalk  路  3Comments

btecu picture btecu  路  3Comments

omariom picture omariom  路  3Comments