Question

I've stackoverflow a ton and never found the need to ask a question before, and while there are a lot of threads on this subject, I can't seem to find something that is easy and makes sense. If I have somehow missed something, please provide a link.

Here goes: I am trying to pass lists back and forth between a python client/server using json, but am condensing the problem into a single block to illustrate:

import json
testdata = ['word','is','bond', False, 6, 99]
# prints normal iterable list
print testdata

myjson = json.dumps(testdata)

#prints [u'word', u'is', u'bond', False, 6, 99], which contains unicode strings
print json.loads(myjson)

# Iterates over each character, since apparently, Python does recognize it is a list
for i in myjson:
    print i

This seems wrong. I passed in an iterable list, and I got out something that can't be used that way. I've seen a lot of answers that suggest that I should just "deal with unicode" which is fine, if I knew how. Either I need a way to force json to load as ascii or utf-8 or something, or a way to allow python to iterate normally over the list containing unicode strings normally.

Thanks!

Was it helpful?

Solution

The problem is that you're iterating over myjson, the string, not over the result of json.loads(myjson), the iterable list.

myjson = json.dumps(testdata)

mydata = json.loads(myjson)
#prints [u'word', u'is', u'bond', False, 6, 99], which contains unicode strings
print mydata
#prints ["word", "is", "bond", false, 6, 99], which is still just a string
print myjson

# Iterates over each character, since it's a string
for i in myjson:
    print i
# Iterates over the list
for i in mydata:
    print i

OTHER TIPS

json.dumps(testdata) is giving you a string... so iterating over the string gives you individual characters. Your code is doing exactly what you're asking it to do.

json.loads does not perform an in-place modification of the variable - so myjson is still a string when you iterate over it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top