snippets
import json
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0, "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json = json.load(teststr)
throws an exception
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'loads'
How to solve a problem?
Conclusion # The Python "AttributeError: 'str' object has no attribute 'read'" occurs when we call the read() method on a string (e.g. a filename) instead of a file object or use the json. load() method by mistake. To solve the error, call the read() method on the file object after opening the file.
loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary.
Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.
JSON files are human-readable means the user can read them easily. These files can be opened in any simple text editor like Notepad, which is easy to use. Almost every programming language supports JSON format because they have libraries and functions to read/write JSON structures.
json.load
takes in a file pointer, and you're passing in a string. You probably meant to use json.loads
which takes in a string as its first parameter.
Secondly, when you import json
, you should take care to not overwrite it, unless it's completely intentional: json = json.load(teststr)
<-- Bad.
This overrides the module that you have just imported, making any future calls to the module actually function calls to the dict that was created.
To fix this, you can use another variable once loaded:
import json
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0, "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json_obj = json.loads(teststr)
OR you can change the module name you're importing
import json as JSON
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0, "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json = JSON.loads(teststr)
OR you can specifically import which functions you want to use from the module
from json import loads
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0, "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json = loads(teststr)
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