-2

I'm reading a JSON with:

# coding: utf8

import urllib2
import json

response = urllib2.urlopen('https://example.com/test.json')
data = json.load(response)

print data['mykey']

# {u'readme': u'Caf\xe9'}

but I see two things:

  • Every string is prefixed with u, i.e. type 'unicode'

  • \xe9 instead of é

How to do this properly with Python 2.7?

Basj
  • 41,386
  • 99
  • 383
  • 673
  • this is only the representation of a dictionary. Printing dictionaries is only for debugging purposes. What is your problem? – Daniel Feb 25 '18 at 15:59
  • Then show code, that really makes some problems (beside printing). – Daniel Feb 25 '18 at 16:05
  • @Basj `"How do this properly with Python 2.7?"` What are you trying to do exactly? You haven't described why the prefix is an issue or why the characters are an issue either. You say you want to "output the data to screen before storing anything in the DB" and one answer shows that you can print it to the screen and my answer shows a way you could save it with the characters intact. What is the issue? What is your actual question? – G_M Feb 25 '18 at 16:16
  • 1
    @DeliriousLettuce: I just discovered my question is in fact an XY problem, because I was displaying output from the SublimeText console. When I display from console with `python myscript.py`, it works, see https://stackoverflow.com/q/48975692/1422096. – Basj Feb 25 '18 at 16:23

1 Answers1

1
>>> import json
>>> d = {u'readme': u'Caf\xe9'}
>>> json.dumps(d)
'{"readme": "Caf\\u00e9"}'
>>> json.dumps(d, ensure_ascii=False)
'{"readme": "Café"}'
G_M
  • 3,342
  • 1
  • 9
  • 23
  • In fact I'm importing data, and not exporting: `json.load(..., ensure_ascii=False)` doesn't exist. How would you do this? – Basj Feb 25 '18 at 16:05