0

When I save with json everything is ok in the file, but when I load the loaded object is not correct.

file=open("hello", "w")

a={'name':'jason', 'age':73, 'grade':{ 'computers':97, 'physics':95, 'math':89} }

json.dump(a, file)

As I said in the file it's ok but when I load you can see a problem.

file:

" {"age": 73, "grade": {"computers": 97, "physics": 95, "math": 89}, "name": "jason"} "

Now the load:

b=json.load(file)

print b

output:

{u"age": 73, u"grade": {u"computers": 97, u"physics": 95, u"math": 89}, u"name": u"jason"}

You can clearly notice that before every string there is u. It's not effecting the code but I don't like it there..

Why is this happening?

karthikr
  • 97,368
  • 26
  • 197
  • 188
Ofek .T.
  • 741
  • 3
  • 10
  • 29

2 Answers2

1

its just in the representation ... its not really there its just signifying that it is unicode

print u"this" == "this"

not sure this needed its own answer:/

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • I know, is there a way to remove it? – Ofek .T. May 14 '13 at 16:38
  • I'm assuming that you're not running python 3.X. I'm fairly certain that you won't see the unicode 'u' if you run it with the python 3.x interpreter...I suppose you could encode it in ascii and use str()? – jheld May 14 '13 at 16:43
  • @Ofek .T.: Why do you want to change the _representation_ of a string? If you just print the data everything is fine. – Matthias May 14 '13 at 18:26
  • Just wanted to why if it is possible – Ofek .T. May 15 '13 at 14:34
0

Here is a function for converting unicode dict to utf8 dict.

def uni2str(input):
    if isinstance(input, unicode):
        return input.encode('utf-8')
    elif isinstance(input, dict):
        return {uni2str(key): uni2str(value) for key, value in input.items()}
    elif isinstance(input, list):
        return [uni2str(element) for element in input]
    else:
        return input

a = {u'name':u'Yarkee', u'age':23, u'hobby':[u'reading', u'biking']}

print(uni2str(a))

The output will be :

{'hobby': ['reading', 'biking'], 'age': 23, 'name': 'Yarkee'}
Yarkee
  • 9,086
  • 5
  • 28
  • 29