9

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

whatever
  • 2,492
  • 6
  • 30
  • 42
  • Check this [Minify Json](https://eliot-jones.com/2014/9/minify-json-net) . You will get a clear idea of Minify a json string. – Partha Jun 01 '18 at 10:09

4 Answers4

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

Andrei
  • 42,814
  • 35
  • 154
  • 218
  • 2
    Thanks Andrei, probably deserializing and re-serializing only to cleanup the generated json is an overkill. Using a regex might still be more efficient. – whatever Jun 01 '18 at 09:38
  • @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 results – Andrei Jun 01 '18 at 12:25
  • @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. – Andrei Jun 01 '18 at 12:43
  • Trying similar thing in .net core 3.1 System.Text.Json but not successful yet – Kamran Shahid Feb 14 '20 at 12:14
5

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
0

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.

aboy021
  • 2,096
  • 2
  • 23
  • 23
-1
var minified = Regex.Replace ( json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1" );

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

Alexis Pautrot
  • 1,128
  • 1
  • 14
  • 18