JSON.NET: minimize / format content without re-parsing

Is it possible to minimize / format the JSON string using the Newtonsoft JSON.NET library without forcing the system to reprocess the code? This is what I have for my methods:

public async Task<string> Minify(string json)
{
    // TODO: Some way to do this without a re-parse?
    var jsonObj = await JsonOpener.GetJsonFromString(json);
    return jsonObj.ToString(Formatting.None);
}

public async Task<string> Beautify(string json)
{
    // TODO: Some way to do this without a re-parse?
    var jsonObj = await JsonOpener.GetJsonFromString(json);
    return FormatJson(jsonObj);
}

private string FormatJson(JToken input)
{
    // We could just do input.ToString(Formatting.Indented), but this allows us
    // to take advantage of JsonTextWriter formatting options.
    using (var stringWriter = new StringWriter(new StringBuilder()))
    {
        using (var jsonWriter = new JsonTextWriter(stringWriter))
        {
            // Configures indentation character and indentation width
            // (e.g., "indent each level using 2 spaces", or "use tabs")
            ConfigureWriter(jsonWriter);
            var serializer = new JsonSerializer();
            serializer.Serialize(jsonWriter, input);

            return stringWriter.ToString();
        }
    }
}

This code works fine in small JSON blocks, but it starts to get caught up in large blocks of content. If I could just cross out everything without missing a parser, it would be much faster, I would think.

If I need to invent a wheel and cross out all the spaces or something else, I will, but I do not know if there are any errors that come into play.

In this regard, is there any other library that is better suited for this?

EDIT: My bad, JSON does not support comments natively.

+4

Source: https://habr.com/ru/post/1679694/


All Articles