Python JSON encoding

KeyboardInterrupt picture KeyboardInterrupt · Jun 11, 2009 · Viewed 151.3k times · Source

I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.

I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.

Currently I am declaring a list, looping through and another list, and appending one list within another:

import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]

x = simplejson.loads(data)
# >>> typeError: expected string or buffer..

x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}

So I either:

  • I don't understand JSON Syntax
  • I don't understand the Pythons JSON module(s)
  • I'm using an inappropriate data type.

Answer

Paolo Bergantino picture Paolo Bergantino · Jun 11, 2009

Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:

>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'