0

Traceback

    dump({'foo':{'bar': 5}}, getwriter('utf8')(f), ensure_ascii=False, encoding='utf8')
  File "/usr/lib/pypy/lib-python/2.7/json/__init__.py", line 196, in dump
    fp.write(chunk)
  File "/usr/lib/pypy/lib-python/2.7/codecs.py", line 370, in write
    self.stream.write(data)
TypeError: unicode argument expected, got 'str'

Code

from __future__ import unicode_literals

from codecs import getwriter
from io import open
from os import path
from tempfile import gettempdir
from json import dump

with open(path.join(gettempdir(), 'bar'), 'wt', encoding='utf8') as f:
    dump({'foo':{'bar': 5}}, getwriter('utf8')(f), ensure_ascii=False,
         encoding='utf8')

(run with ideone)

A T
  • 13,008
  • 21
  • 97
  • 158
  • Is the only [solution](https://stackoverflow.com/a/18337754) to use `json.dumps`, or is there a way of using `json.dump`? – A T Jan 08 '18 at 05:09

1 Answers1

0

That's weird, changing the import from:

from io import open

To:

from codecs import open

Did the trick. Even though https://stackoverflow.com/a/844443 said the first is new best-practice :\

A T
  • 13,008
  • 21
  • 97
  • 158