AttributeError: 'str' object has no 'load' attributes, json.loads ()

fragments

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?

+7
source share
1 answer

json.load takes a file pointer, and you pass a string. You probably json.loads use json.loads which takes a string as the first parameter.

Secondly, when you import json , you should take care not to overwrite it if it is not completely intentional: json = json.load(teststr) <- Bad . This overrides the module you just imported, making any future module calls actually function calls to the created dict.

To fix this, you can use another variable after loading:

 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 name of the module you are 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) 
+19
source

All Articles