Python AttributeError: 'str' 对象没有属性 'loads', json.loads()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38307724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:37:31  来源:igfitidea点击:

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

pythonjson

提问by Artem Malikov

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?

如何解决问题?

回答by Sunny Patel

json.loadtakes in a file pointer, and you're passing in a string. You probably meant to use json.loadswhich takes in a string as its first parameter.

json.load接收一个文件指针,然后传入一个字符串。您可能打算使用json.loadswhich 接受一个字符串作为其第一个参数。

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.

其次,当你import json,你应该注意不要覆盖它,除非它完全是故意的:json = json.load(teststr)<-- Bad。这将覆盖您刚刚导入的模块,使以后对该模块的任何调用实际上都是对创建的 dict 的函数调用。

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)

ORyou 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)

ORyou 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)