GitHub Actions Workflow Functions: Understanding toJSON and fromJSON with Examples

GitHub Actions Workflow Functions: Understanding toJSON and fromJSON with Examples

Hello GitHub enthusiasts! Today, we’ll be exploring two key functions used in GitHub Actions workflows: toJSON and fromJSON. These functions allow us to handle JSON data within workflows, opening up a whole range of possibilities for data manipulation and storage.

Understanding the toJSON and fromJSON Functions

In GitHub Actions, the toJSON function converts a GitHub context, an array, or a map to a JSON string, while the fromJSON function parses a JSON string into an object that can be used within your workflow.

Here’s the syntax for these functions:

  • toJSON(expression): Returns a JSON string representation of the expression.
  • fromJSON(json): Parses the json string into an object.

Now, let’s look at some examples of how to use these functions in your workflows.

Using toJSON

Suppose we want to convert the GitHub context object to a JSON string to better understand its structure. Here’s how you might do this:

In this case, the toJSON function converts the entire github context into a JSON string, which is then printed to the console.

Using fromJSON

On the other hand, fromJSON can be used to parse JSON data into an object. This is especially useful when working with output from previous steps or jobs that is in JSON format. For example, consider a job where a previous step returned a JSON string as output:

Here, fromJSON is used to parse the JSON string output from the generate-output step into an object. The key field of this object is then printed to the console.

Using toJSON and fromJSON Together

These two functions can also be used together for storing and retrieving complex data (like arrays or objects) in a single job or across different jobs. This is because outputs can only be string data, so toJSON can be used to convert the data into a storable format, and fromJSON to parse the data when needed:

Conclusion

The toJSON and fromJSON functions in GitHub Actions enable you to effectively handle JSON data within your workflows. Mastering these functions will allow you to manipulate complex data types, enhance your CI/CD processes, and adapt your workflows to a variety of data-centric tasks.

Remember, GitHub Actions offers a broad range of powerful functions and features. By combining them creatively, you can create highly tailored workflows that perfectly fit your project’s unique needs. Happy coding!