Using System.Text.Json i can pretty print json using serialization option.
var options = new JsonSerializerOptions{ WriteIndented = true };
jsonString = JsonSerializer.Serialize(typeToSerialize, options);
However, I have string JSON and don't know the concrete type. Ho do I pretty-print JSON string?
My old code was using Newtonsoft and I could do it without serialize/deserialize
public static string JsonPrettify(this string json)
{
if (string.IsNullOrEmpty(json))
{
return json;
}
using (var stringReader = new StringReader(json))
using (var stringWriter = new StringWriter())
{
var jsonReader = new JsonTextReader(stringReader);
var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
jsonWriter.WriteToken(jsonReader);
return stringWriter.ToString();
}
}
Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.
Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .
This works:
using System.Text.Json;
public static string JsonPrettify(this string json)
{
using var jDoc = JsonDocument.Parse(json);
return JsonSerializer.Serialize(jDoc, new JsonSerializerOptions { WriteIndented = true });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With