[Tutor] Parsing JSON with Python

Martin A. Brown martin at linux-ip.net
Fri Dec 12 00:22:12 CET 2014


Hello there,

> To whom it may concern,
>
> I am having difficulty interacting with JSON. The example below if a
> typical input and output:
>
>
> *import json*
> *array = json.load( { "name": "Joe", "address": "111 Street" } )*
>
> *Traceback (most recent call last): File "<stdin>" , line 1, in <module>
> File "C:\Python27\lib\json\__init__.py" , line 286, in load return
> loads(fp.read(), AttributeError: 'dict' object has no attribute 'read' >>>*
>
>
> I would appreciate assitance understanding why this doesn't work, 
> and how I can get up-and-running with inputing JSON code into 
> Python.

Which version of Python?  The following works with Python 3.x and 
Python 2.7, though:

   arr = json.loads('{ "name": "Joe", "address": "111 Street" }')
   arr.get('address')

Here are some notes about why:

   # -- below is a Python dictionary, it is not actually JSON

   >>> { "name": "Joe", "address": "111 Street" }
   {'name': 'Joe', 'address': '111 Street'}


   # -- next is that Python dictionary turned into JSON (single quotes)

   >>> '{ "name": "Joe", "address": "111 Street" }'
   '{ "name": "Joe", "address": "111 Street" }'


   # -- now you have a JavaScript Object Notation string, which you
   #    can manipulate; let's use the json.loads() call

   >>> arr = json.loads('{ "name": "Joe", "address": "111 Street" }')


   # -- You will notice I used a variable called 'arr' instead of
   #    array, because there is a module called array, and I may
   #    (one day) want to use it.

   >>> arr
   {'name': 'Joe', 'address': '111 Street'}


   # -- OK, but I'm lazy, I don't want to have to type all of my
   #    JSON into strings.  OK.  So, don't.  Have the JSON module
   #    convert your object (a dictionary) into a string for you.

   >>> json.dumps(arr)
   '{"name": "Joe", "address": "111 Street"}'

So, have some fun with the json.dumps() and json.loads() calls. 
Then, you can move on to json.dump() and json.load() to put your 
data into files.

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list