Reputation: 3687
How can an existing json string be cleaned up/minfied? I've seen regexes being used. Any other (maybe more efficient) approach?
Upvotes: 13
Views: 22521
Reputation: 493
With System.Text.Json
this works:
var jsonString = " { \n\r\t\"title\": \"Non-minified JSON string\"\n\r } ";
var minifiedJsonString = JsonNode.Parse(jsonString)?.ToJsonString();
Console.WriteLine(minifiedJsonString);
// Output {"title":"Non-minified JSON string"}
Upvotes: 1
Reputation: 2596
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
Upvotes: 0
Reputation: 489
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
Upvotes: 11
Reputation: 2305
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
.
Upvotes: 1
Reputation: 1165
var minified = Regex.Replace ( json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1" );
Found from here : https://github.com/MatthewKing/JsonFormatterPlus/blob/master/src/JsonFormatterPlus/JsonFormatter.cs
Upvotes: -1
Reputation: 44660
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
.
Upvotes: 17