Notice how there is a string with some metadata for each field. This tells Go what each field is named in your JSON. After this, you can include the encoding/JSON library you get a whole host of functions including:

Notice the only change is in the metadata. Now it specifies YAML and not JSON, but the intent is the same. What name does the field have in the YAML? To interact with it there is a marshal and unmarshal function:

Above is a complete example. The lib is imported and a struct called Person created. Then in the main function, a person variable is instantiated to the type Person – a struct object.

On line 20 the data variable – containing some valid YAML – is read into the person variable using the Marshal function.

On line 23 this person variable is converted back into JSON using the Unmarshal function and stored in the personJSON variable. Both functions are members of the YAML class which is introduced by the lib.

Supporting JSON and YAML

In my use case, there was not a need to support both JSON and YAML. But if you need to then check out the write up The right way to handle YAML in Go by Sam Ghods which was an interesting read – it should set you on the right path.