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'
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.
__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.
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.
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With