Search code examples
jsonyamlfile-conversionballerina

How to Convert a JSON value to YAML value in Ballerina


Is there a way to convert a JSON value to a YAML value in Ballerina?

Consider the following sample JSON file:

{
    "user": {
        "name": "John Doe",
        "email": "[email protected]",
        "age": 20
    },
    "product": {
        "name": "Shoes",
        "price": 100
    }
}

The requirement is to first convert this into YAML format.

user:
  name: John Doe
  email: [email protected]
  age: 20
product:
  name: Shoes
  price: 100

Then encode this into base64 encoding. Tried the ballerina/yaml library, but seems like there is no direct way to do this.


Solution

  • This can be done by using the ballerina/io, ballerina/mime, and ballerina/yaml libraries. Following is an example code for doing this. Consider a sample.json file in the resources directory.

    import ballerina/io;
    import ballerina/mime;
    import ballerina/yaml;
    
    public function main() returns error? {
        // Read the JSON file
        json jsonValue = check io:fileReadJson("resources/sample.json");
    
        // Convert the JSON value to the YAML value
        string yamlValue = check convertToYaml(jsonValue);
    
        // Encode the YAML string into base64 encoding
        string encodedString = check (check mime:base64Encode(yamlValue)).ensureType();
    
        io:println(encodedString);
    }
    
    function convertToYaml(json input) returns string|error {
        // Converting the JSON value into a YAML value.
        // This returns an array of YAML values.
        // The blockLevel indicates the maximum depth level for a block
        string[] yamlArray = check yaml:writeString(input, blockLevel = 10);
    
        // Finally, we join the array using a new line character to build the YAML string
        return string:'join("\n", ...yamlArray);
    }
    

    Read more about the yaml:writeString() function in the YAML module API docs.