TypeError:JSON对象必须是str,而不是' dict'

时间:2017-03-20 09:01:23

标签: python json python-3.x

对不起伙计们,我无法找到令人满意的答案来打印部分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的回应是

{
    "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
}

现在,我想遍历并仅打印&#34;数据&#34;:值。我将做以下

data = json.loads(json_data)
data_set = (data['data'])
print(data_set)

但我得到的错误:TypeError:JSON对象必须是str,而不是&#39; dict&#39;

2 个答案:

答案 0 :(得分:11)

你不需要<spring:beans xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://membrane-soa.org/proxies/1/" spring:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" /> ,因为它已经是一个python dict,你只需要直接输出这个dict。从dict输出json字符串是json.loads(json_data)的工作:

json.dumps()

答案 1 :(得分:0)

实际上json()方法会返回 json 对象,因此您不需要使用json.loads

或者您可以使用

r=requests.get("")
print json.loads(r.content)

查看JSON Response Content的更多详情。