How to convert YAML to JSON?

I want to convert a YAML and JSON file. It was really hard to find any information.

+4
source share
2 answers

If you don't need Json.NET functions, you can also use the Serializer class to emit JSON:

// now convert the object to JSON. Simple!
var js = new Serializer(SerializationOptions.JsonCompatible);

var w = new StringWriter();
js.Serialize(w, o);
string jsonText = w.ToString();

Here you can check two working scripts:

+3
source

This can be done using the built-in JSON library along with YamlDotNet. This was not obvious in the YamlDotNet documentation, but I found a way to do this quite simply.

// convert string/file to YAML object
var r = new StreamReader(filename); 
var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
var yamlObject = deserializer.Deserialize(r);

// now convert the object to JSON. Simple!
Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();

var w = new StringWriter();
js.Serialize(w, o);
string jsonText = w.ToString();

I was surprised that it worked as well as it did! The JSON output was identical to other web tools.

+1
source

Source: https://habr.com/ru/post/1589126/


All Articles