Galen
Galen

Reputation: 1352

'dict' object has no attribute 'read'

Running Python on a Windows system I encountered issues with loading a JSON file into memory. What is wrong with my code?

>>> import json
>>> array = json.load({"name":"Name","learning objective":"load json files for data analysis"})
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    array = json.load({"name":"Name","learning objective":"load json files for data analysis"})
  File "C:\Python34\lib\json\__init__.py", line 265, in load
    return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'

Upvotes: 15

Views: 133460

Answers (3)

lauralacarra
lauralacarra

Reputation: 620

As you said, it is wrong, you forgot the ' before and after the json text.

import json
array = json.load('{"name":"Galen","learning objective":"load json files for data analysis"}')

I had the same mistake :)

dumps works but it is not the same. Load is better for parsing json. https://docs.python.org/2/library/json.html

Upvotes: -2

Gerardo
Gerardo

Reputation: 7767

if you want to load json from a string you need to add quotes around your string and there is a different method to read from file or variable. For variable it ends with "s" other doesn't

import json

my_json = '{"my_json" : "value"}'

res = json.loads(my_json)
print res

Upvotes: 1

Archit Verma
Archit Verma

Reputation: 1917

Since you want to convert it into json format, you should use json.dumps() instead of json.load(). This would work:

>>> import json
>>> array = json.dumps({"name":"Galen","learning objective":"load json files for data analysis"})
>>> array
'{"learning objective": "load json files for data analysis", "name": "Galen"}'

Output:

>>> a = json.loads(array)
>>> a["name"]
u'Galen'

Upvotes: 31

Related Questions