Skip to content

Instantly share code, notes, and snippets.

@hiranp
Created May 26, 2023 15:30
Show Gist options
  • Save hiranp/27838201853e55ae29494b1f2c0c836d to your computer and use it in GitHub Desktop.
Save hiranp/27838201853e55ae29494b1f2c0c836d to your computer and use it in GitHub Desktop.
Python JSON to Yaml convertor
def convert_json_to_yaml(json_string: str) -> str:
"""Converts a JSON string to YAML format.
Handles both JSON objects and arrays.
Args:
json_string: The JSON string to convert.
Returns:
The YAML representation of the JSON string.
Raises:
yaml.YAMLError: If the JSON string is not valid YAML.
"""
try:
python_obj = yaml.safe_load(json_string)
except yaml.YAMLError as e:
raise ValueError(f"The JSON string is not valid YAML: {e}")
if isinstance(python_obj, list):
yaml_string = yaml.dump(python_obj, default_flow_style=False)
else:
yaml_string = yaml.dump(python_obj)
return yaml_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment