Discussion:
[Tutor] Parsing JSON with Python
Galen Seilis
2014-12-11 20:25:53 UTC
Permalink
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.
--
Galen
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Ben Finney
2014-12-11 23:15:54 UTC
Permalink
Post by Galen Seilis
I am having difficulty interacting with JSON. The example below if a
Thank you for presenting a simple example and the resulting output.

Unfortunately, your mail client has mangled it, inserting asterisks
making syntax errors, and wrapping lines that should be separate.

Please, in future, compose messages only in “plain text” mode. Your text
examples will survive much better that way.
Post by Galen Seilis
*import json*
*array = json.load( { "name": "Joe", "address": "111 Street" } )*
You are passing a Python dict value to the function. JSON is a
serialisation format, and the input to ‘json.load’ must be a text
string.

A literal Python text string looks like this in the code::

"foo bar baz"

A literal Python dict looks like this in the code::

{ "name": "Joe", "address": "111 Street" }
--
\ “For fast acting relief, try slowing down.” —Jane Wagner, via |
`\ Lily Tomlin |
_o__) |
Ben Finney

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
ht
Alan Gauld
2014-12-11 23:23:01 UTC
Permalink
Post by Ben Finney
Post by Galen Seilis
*array = json.load( { "name": "Joe", "address": "111 Street" } )*
You are passing a Python dict value to the function. JSON is a
serialisation format, and the input to ‘json.load’ must be a text
string.
Nope, its a file-like object.

The input to loads() is a text string.
The implementation of load() apparently reads the file object
to produce a string which is passed to loads()
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/
Ben Finney
2014-12-11 23:29:38 UTC
Permalink
Post by Alan Gauld
Post by Ben Finney
Post by Galen Seilis
*array = json.load( { "name": "Joe", "address": "111 Street" } )*
You are passing a Python dict value to the function. JSON is a
serialisation format, and the input to ‘json.load’ must be a text
string.
Nope, its a file-like object.
Fair enough, I didn't check the ‘json.load’ documentation. Thank you for
the correction.

I suspect the OP wasn't aware they specified a Python dict, though,
which is the main point.
--
\ “Never use a long word when there's a commensurate diminutive |
`\ available.” —Stan Kelly-Bootle |
_o__) |
Ben Finney

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
Alan Gauld
2014-12-11 23:19:30 UTC
Permalink
Post by Galen Seilis
To whom it may concern,
I am having difficulty interacting with JSON. The example below if a
*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' >>>*
The documentation for json.load() says:

######################
json.load(fp, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize fp (a .read()-supporting file-like object containing a JSON
document) to a Python object using this conversion table.
...
#####################

So it expects a file-like object as its first argument but you are
passing a dictionary.

It's not clear whether you are trying to convert your dictionary into a
json data stream or whether you are trying to read a json string and
convert it to a Python dictionary. Whichever way round you won't get
an array back.

dumps() will turn a Python data structure into a JSON string.
loads() will turn a JSON string into a Python object. I'm guessing
this is what you wanted?

Just remember that the 's' at the end signifies string not a plural.
And the non-s versions use files not strings.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Martin A. Brown
2014-12-11 23:22:12 UTC
Permalink
Hello there,
Post by Galen Seilis
To whom it may concern,
I am having difficulty interacting with JSON. The example below if a
*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
Post by Galen Seilis
Post by Galen Seilis
{ "name": "Joe", "address": "111 Street" }
{'name': 'Joe', 'address': '111 Street'}


# -- next is that Python dictionary turned into JSON (single quotes)
Post by Galen Seilis
Post by Galen Seilis
'{ "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
Post by Galen Seilis
Post by Galen Seilis
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.
Post by Galen Seilis
Post by Galen Seilis
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.
Post by Galen Seilis
Post by Galen Seilis
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/
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2014-12-11 23:56:10 UTC
Permalink
Post by Martin A. Brown
arr = json.loads('{ "name": "Joe", "address": "111 Street" }')
arr.get('address')
# -- 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'}
But even arr is a bad name choice because it implies an array
structure is being stored, which it isn't, it's a dictionary
(which in the general case can be called an "associative array"
but in Python-land that's extremely rare). arrays are a very
specific type of data and using a variable name that sounds
like array is liable to lead to false assumptions further down
the line.

Since this data stores a name and address use a name that reflects that,
such as location, home, or even just address... Names should nearly
always reflect their logical purpose not their data type.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2014-12-11 23:51:56 UTC
Permalink
Post by Galen Seilis
I would appreciate assitance understanding why this doesn't work, and how I
can get up-and-running with inputing JSON code into Python.
Did you try reading the Fine Manual? It has many examples!

For Python 2:
https://docs.python.org/2/library/json.html

or for Python 3:
https://docs.python.org/3/library/json.html


The four functions you are likely to care about are:

json.load # read JSON input from a file, return objects
json.loads # read JSON input from a string, return objects
json.dump # dump JSON output to a file
json.dumps # dump JSON output to a string


Example:

py> import json
py> data = {23: None, 42: "Hello World!"}
py> s = json.dumps(data)
py> print(s)
{"42": "Hello World!", "23": null}
py> obj = json.loads(s)
py> print(obj)
{'23': None, '42': 'Hello World!'}
--
Steven
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...