Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify a json string using .NET

Tags:

json

.net

minify

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

like image 929
whatever Avatar asked Feb 02 '26 06:02

whatever


2 Answers

You can just serialize and deserialize non-minified JSON, you'll get a minified version at the end of it via most serializers.

Using Built-In System.Text.Json

var json = "  {  \"title\": \"Non-minified JSON string\"  }  ";
var doc = JsonDocument.Parse(json);
var minified = JsonSerializer.Serialize(doc);

Using Newtonsoft.Json

Install-Package Newtonsoft.Json

Just parse it and then serialize back into JSON:

var json = "  {  title: \"Non-minified JSON string\"  }  ";
var obj = JsonConvert.DeserializeObject(json);
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.

like image 54
Andrei Avatar answered Feb 04 '26 23:02

Andrei


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
like image 42
NullPointerWizard Avatar answered Feb 05 '26 00:02

NullPointerWizard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!