python – dump json into yaml

python – dump json into yaml

pyyaml.dump() has allow_unicode option, its 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 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 doesnt do inline – so you have dumpable data ready.

Takes care of unicode as per How to get string objects instead of Unicode from JSON?

python – dump json into yaml

In [1]: import json, yaml

In [2]: with open(test.json) as js:
   ...:     data = json.load(js)[umain]
   ...:     

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: 今日は雨が降って}

Leave a Reply

Your email address will not be published. Required fields are marked *