Skip to content

Instantly share code, notes, and snippets.

@noahcoad
Last active November 3, 2023 11:40
Show Gist options
  • Save noahcoad/46909253a5891af3699580b8f17baba8 to your computer and use it in GitHub Desktop.
Save noahcoad/46909253a5891af3699580b8f17baba8 to your computer and use it in GitHub Desktop.
Python to convert json to yaml
#!/usr/bin/env python3
# convert json to yaml
# http://pyyaml.org/wiki/PyYAMLDocumentation
# python3 json2yaml.py < ~/code/manpow/moneybug/mbuploader/support/offices.json
# gist https://gist.github.com/noahcoad/46909253a5891af3699580b8f17baba8
import yaml, json, sys
sys.stdout.write(yaml.dump(json.load(sys.stdin)))
@FilBot3
Copy link

FilBot3 commented Aug 24, 2020

Works like a Charm, however, running it through Pylint and Pycodestyle and autopep8, I have mine looking like...

#!/usr/bin/env python3
"""convert json to yaml
http://pyyaml.org/wiki/PyYAMLDocumentation
python3 json2yaml.py < ~/code/manpow/moneybug/mbuploader/support/offices.json
gist https://gist.github.com/noahcoad/46909253a5891af3699580b8f17baba8
"""


import json
import sys
import yaml


sys.stdout.write(yaml.dump(json.load(sys.stdin)))

Usage

cat azurerm-template.json | python json2yaml.py | tee azurerm-template.yaml

@aanagnostou
Copy link

If we want to preserve the order of the json file and we have PyYAML >= 5.1...

#!/usr/bin/env python3
"""convert json to yaml
Documentation : https://pyyaml.org/wiki/PyYAML
Version 5.1 (2019-03-13) #254 – Allow to turn off sorting keys in Dumper
python3 json2yaml.py < ~/code/manpow/moneybug/mbuploader/support/offices.json
gist https://gist.github.com/noahcoad/46909253a5891af3699580b8f17baba8
"""


import json
import sys
import yaml


sys.stdout.write(yaml.dump(json.load(sys.stdin),sort_keys=False))

Usage

cat azurerm-template.json | python json2yaml.py | tee azurerm-template.yaml

@rnivash
Copy link

rnivash commented Sep 3, 2021

To format yaml file

#!/usr/bin/env python3
# to format yaml file
# http://pyyaml.org/wiki/PyYAMLDocumentation


import yaml, json, sys
sys.stdout.write(yaml.dump(yaml.load(sys.stdin)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment