3

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

whatever
  • 1,514
  • 3
  • 17
  • 36
  • 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

1 Answers1

5
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
  • 40,274
  • 34
  • 151
  • 206
  • 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