dump json into yaml

This works for me:

#!/usr/bin/env python

import sys
import json
import yaml

print(yaml.dump(json.load(open(sys.argv[1])), 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 from JSON?


pyyaml.dump() has an allow_unicode option that defaults to None (all non-ASCII characters in the output are escaped). If allow_unicode=True, then it writes raw Unicode strings.

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

Bonus

You can dump JSON without encoding as follows:

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