Converting JSON into Python dict Converting JSON into Python dict django django

Converting JSON into Python dict


  • Use the json module for loading JSON. (Pre-2.6 use the third party simplejson module, which has the same exact API.)

    >>> import json>>> s = '{"foo": 6, "bar": [1, 2, 3]}'>>> d = json.loads(s)>>> print d{u'foo': 6, u'bar': [1, 2, 3]}
  • Your actual data cannot be loaded this way since it's actually two JSON objects separated by a comma and with a trailing comma. You'll need to separate them or otherwise deal with this.

    • Where did you get this string?


The string you show is not a JSON-coded object (eqv to a Python dict) — more like an array (eqv to a list) without brackets and with a stray extra comma at the end. So (using simplejson for version portability — the standard library's json in 2.6 is fine too of course!-):

>>> import simplejson>>> js = "{\"description\":\"fdsafsa\",\"order\":\"1\",\"place\":\"22 Plainsman Rd, Mississauga, ON, Canada\",\"lat\":43.5969175,\"lng\":-79.7248744,\"locationDate\":\"03/24/2010\"},{\"description\":\"sadfdsa\",\"order\":\"2\",\"place\":\"50 Dawnridge Trail, Brampton, ON, Canada\",\"lat\":43.7304774,\"lng\":-79.8055435,\"locationDate\":\"03/26/2010\"},">>> simplejson.loads('[%s]' % js[:-1])[{'description': 'fdsafsa', 'order': '1', 'place': '22 Plainsman Rd, Mississauga, ON, Canada', 'lat': 43.596917500000004, 'lng': -79.724874400000004, 'locationDate': '03/24/2010'}, {'description': 'sadfdsa', 'order': '2', 'place': '50 Dawnridge Trail, Brampton, ON, Canada', 'lat': 43.730477399999998, 'lng': -79.805543499999999, 'locationDate': '03/26/2010'}]

If you really want a dict you'll have to specify how to treat these two unnamed items, i.e., what arbitrary keys you want to slap on them...?


django.utils.simplejson.loads(someJson)