简体   繁体   中英

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM