Created
May 26, 2023 15:30
-
-
Save hiranp/27838201853e55ae29494b1f2c0c836d to your computer and use it in GitHub Desktop.
Python JSON to Yaml convertor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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