Python 类型错误:JSON 对象必须是 str,而不是 'dict'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42899389/
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
TypeError: the JSON object must be str, not 'dict'
提问by Manoj Kengudelu
Sorry guys, I couldn't find the satisfying answer to print part of json response. Can someone help me here please:
对不起,我找不到满意的答案来打印部分 json 响应。有人可以在这里帮助我吗:
import json
import requests
import pprint
response = requests.get('<api endpoing>')
json_data = response.json()
print(json.dumps(json_data, indent=4, sort_keys=True))
Json response would be
Json 响应将是
{
"Value1": "SomeValue",
"data": {
"subval1": false,
"subval2": "0a4",
"subval3": "",
"subval4": "Click h!",
"subval5": "1002",
"subval6": "932",
"subval7": "i2",
"subval8": 250,
"subval9": 0,
"subval10": 1,
"subval11": 3,
"subval12": 1,
"subval13": "<!>",
"subval14": "",
"subval15": "Click !!",
"subval16": "",
"subval17": 300
},
"error": true,
"message": "Success",
"status": 200
}
Now, I would like to traverse and print only the "data": values. I will do the following
现在,我只想遍历和打印“数据”:值。我会做以下事情
data = json.loads(json_data)
data_set = (data['data'])
print(data_set)
But the error Im getting: TypeError: the JSON object must be str, not 'dict'
但是我得到的错误:TypeError: the JSON object must be str, not 'dict'
回答by n00dl3
You don't need to json.loads(json_data)
as it is already a python dict, you just need to output this dict directly. And outputing json string from a dict is json.dumps()
's job :
你不需要,json.loads(json_data)
因为它已经是一个python dict,你只需要直接输出这个dict。从 dict 输出 json 字符串是json.dumps()
工作:
json.dumps(json_data["data"])
回答by McGrady
Actually json()
method returns a jsonobject,so you don't need to use json.loads
实际上json()
方法返回一个json对象,所以你不需要使用json.loads
Or you can use
或者你可以使用
r=requests.get("")
print json.loads(r.content)
See more details from JSON Response Content.
从JSON 响应内容中查看更多详细信息。