Programming

Google Cloud Function to convert YAML to JSON

TLDR: Just posted this little Google Cloud Function to https://github.com/krypted/tinyconverters/blob/main/YAML_to_JSON.py.

This Google Cloud Function converts YAML to JSON. The function takes YAML as input, uses the yaml and json modules, and returns the JSON data. The function below should be deployed as a Python 3.7 runtime: 

import yaml
import json

def main(event, context):
  # Get the YAML data from the event
  yaml_data = event['data']

  # Convert the YAML data to JSON
  json_data = json.dumps(yaml.safe_load(yaml_data))

  # Return the JSON data
  return json_data

Once the function is deployed, call it by sending a POST request to the function’s URL with the YAML:

curl -X POST -H "Content-Type: application/yaml" -d '
name: Chuck U Farley
age: 17
' https://us-central1-my-project.cloudfunctions.net/yaml-to-json

The response body contains the JSON data as follows:

{
  "name": "Chuck U Farley",
  "age": 17
}