Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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'
like image 474
AgnesianOperator Avatar asked Dec 11 '14 04:12

AgnesianOperator


People also ask

Has no attribute dict?

The "AttributeError: 'dict' object has no attribute" means that we are trying to access an attribute or call a method on a dictionary that is not implemented by the dict class.

What is self __ dict __ Python?

__dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects.

What is JSON load?

json. load() takes a file object and returns the json object. A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon.


2 Answers

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'
like image 112
Archit Verma Avatar answered Sep 21 '22 02:09

Archit Verma


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
like image 26
Gerardo Avatar answered Sep 21 '22 02:09

Gerardo