dump json into yaml dump json into yaml json json

dump json into yaml


pyyaml.dump() has "allow_unicode" option, it's default is None,all non-ASCII characters in the output are escaped. If allow_unicode=True write raw unicode strings.

yaml.dump(data, ff, allow_unicode=True)

bonus

json.dump(data, outfile, ensure_ascii=False)


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:

  1. load json file through json.loads
  2. json loads in unicode format - convert that to string by json.dump
  3. load the yaml through yaml.load
  4. 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: 今日は雨が降って}