Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert YAML to JSON?

I'm looking to convert between a YAML file, and JSON. This was really difficult to find any information on.

like image 947
Michael Brown Avatar asked May 21 '15 04:05

Michael Brown


2 Answers

If you do not need the features of Json.NET, you can also use the Serializer class directly 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();

You can check two working fiddles here:

  • Convert YAML to JSON
  • Convert YAML to JSON using Json.NET
like image 154
Antoine Aubry Avatar answered Oct 06 '22 01:10

Antoine Aubry


It is possible to do this by using the built-in JSON library along with YamlDotNet. It wasn't apparent in the YamlDotNet documentation, but I found a way to do it rather 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, yamlObject);
string jsonText = w.ToString();

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

like image 30
Michael Brown Avatar answered Oct 06 '22 00:10

Michael Brown