dump json into yaml
This works for me:
#!/usr/bin/env pythonimport sysimport jsonimport yamlprint yaml.dump(yaml.load(json.dumps(json.loads(open(sys.argv[1]).read()))), default_flow_style=False)
So what we are doing is:
- load json file through json.loads
- json loads in unicode format - convert that to string by json.dump
- load the yaml through yaml.load
- dump the same in a file through yaml.dump - default_flow_style - True displays data inline, False doesn't do inline - so you have dumpable data ready.
Takes care of unicode as per How to get string objects instead of Unicode ones from JSON in Python?
In [1]: import json, yamlIn [2]: with open('test.json') as js: ...: data = json.load(js)[u'main'] ...: In [3]: with open('test.yaml', 'w') as yml: ...: yaml.dump(data, yml, allow_unicode=True) ...: In [4]: ! cat test.yaml{!!python/unicode 'description': 今日は雨が降って, !!python/unicode 'title': 今日は雨が降って}In [5]: with open('test.yaml', 'w') as yml: ...: yaml.safe_dump(data, yml, allow_unicode=True) ...: In [6]: ! cat test.yaml{description: 今日は雨が降って, title: 今日は雨が降って}