Minify a json string using .NET
Asked Answered
B

5

12

How can an existing json string be cleaned up/minfied? I've seen regexes being used. Any other (maybe more efficient) approach?

Backing answered 31/5, 2018 at 22:12 Comment(1)
Check this Minify Json . You will get a clear idea of Minify a json string.Tourer
O
15
Install-Package Newtonsoft.Json

Just parse it and then serialize back into JSON:

var jsonString = "  {  title: \"Non-minified JSON string\"  }  ";
var obj = JsonConvert.DeserializeObject(jsonString);
jsonString = JsonConvert.SerializeObject(obj);

SerializeObject(obj, Formatting.None) method accepts Formatting enum as a second parameter. You can always choose if you want Formatting.Indented or Formatting.None.

Outlying answered 31/5, 2018 at 22:17 Comment(4)
Thanks Andrei, probably deserializing and re-serializing only to cleanup the generated json is an overkill. Using a regex might still be more efficient.Backing
@noplace I doubt it, regardless of the approach you have to read through the whole json, and regex has never been great for performance. Serialization back and forth wouldn't be super-fast either but Json.NET typically demonstraits good resultsOutlying
@noplace also please note, I'm not deserializing to a specific type, it means it will result to internal Json.NET JObject - this avoids a lot of reflection and processing to match properties and types.Outlying
Trying similar thing in .net core 3.1 System.Text.Json but not successful yetDubois
S
9

Very basic extension method using System.Text.Json

using System.Text.Json;
using static System.Text.Json.JsonSerializer;

public static class JsonExtensions
{
    public static string Minify(this string json)
        => Serialize(Deserialize<JsonDocument>(json));
}

This takes advantages of default value of JsonSerializerOptions

JsonSerializerOptions.WriteIndented = false
Selia answered 27/1, 2023 at 11:16 Comment(0)
A
1

If you're using System.Text.Json then this should work:

private static string Minify(string json)
{
    var options =
        new JsonWriterOptions
        {
            Indented = false,
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };
    using var document = JsonDocument.Parse(json);
    using var stream = new MemoryStream();
    using var writer = new Utf8JsonWriter(stream, options);
    document.WriteTo(writer);
    writer.Flush();
    return Encoding.UTF8.GetString(stream.ToArray());
}

The Encoder option isn't required, but I ended up going this way so that characters aren't quite so aggressively escaped. For example, when using the default encoder + is replaced by \u002B44.

Avera answered 21/9, 2022 at 3:43 Comment(1)
Looks like JsonSerializer.Serialize(JsonSerializer.Deserialize<JsonDocument>())Estreat
U
0

For my use case, I am minifying large-ish objects, about 15k characters with a fairly deep hierarchy. Most of existing answers to this question work and remove about 25% of the unnecessary characters. Performance is an issue for me and it turns out that serialising and then deserialising seems to add a significant overhead.

I performed some fairly crude tests: I recorded how long it took to sequentially minify 1 million of my objects. I did not monitor memory usage to be fair. The code below did the job in about 60% of the time taken by the next best option:

using Newtonsoft.Json;
using System.IO;

public static string Minify(string json)
{
    using (StringReader sr = new StringReader(json))
    using (StringWriter sw = new StringWriter())
    using (JsonReader reader = new JsonTextReader(sr))
    using (JsonWriter writer = new JsonTextWriter(sw))
    {
        writer.Formatting = Formatting.None;
        writer.WriteToken(reader);
        return sw.ToString();
    }
}

Credit where it's due, my code is adapted from this answer

Upswell answered 14/9, 2023 at 11:23 Comment(0)
F
-1
var minified = Regex.Replace ( json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1" );

Found from here : https://github.com/MatthewKing/JsonFormatterPlus/blob/master/src/JsonFormatterPlus/JsonFormatter.cs

Fixity answered 24/7, 2022 at 11:32 Comment(1)
This is a brittle solution. The other approaches here would be preferable, I'd say.Rudbeckia

© 2022 - 2024 — McMap. All rights reserved.