【问题标题】:Parse string from an array. Error Code: 'json' has no attribute 'str'从数组中解析字符串。错误代码:“json”没有属性“str”
【发布时间】:2021-10-02 06:13:49
【问题描述】:

如何从数组中获取字符串结果?

我的代码如下所示:

#Start 10 highest Results

print("High Results:")
print("Doing request")

headers = {"content-type": "application/json", "Accept-Charset": "UTF-8", "ApiAccessKey": "ExampleKey", "ApiSecretKey": "Example Key"}
response = requests.get("https://www.example.com/", headers=headers, verify=False)
print("writing response code")
print(response)

print(response.content ) # Return the raw bytes of the data payload
print("----------------------------------")

json_object = json.loads(response.text)
json_formatted_str = json.dumps(json_object, indent=2)
print(json_formatted_str)

y = json.str(response.content)

#Display only High Results
print(y[0]["High"])

print("done")

我得到的错误:

Traceback (most recent call last):
File "./CurlRequest.py", line 71, in <module>
y = json.str(response.content)
AttributeError: module 'json' has no attribute 'str'

【问题讨论】:

    标签: python arrays json string curl


    【解决方案1】:

    如果您知道响应是 JSON,那么您只需执行 y = response.json()。之后,如果您想过滤掉y 中字段RiskLevel 等于"High" 的所有条目,您可以这样做:

    for key in y:
       if y[key]["RiskLevel"] == "High":
          # do something with the entry
          print(y[key])
    

    【讨论】:

    • 现在我得到KeyError: 0
    • 只需print(y) 并发布结果,否则无法为您提供帮助。显然y 是字典而不是数组。
    • 我可以执行 print(y[High]) 以仅过滤名称为 High 的结果。因为有中等和高的结果,但我只需要高的
    • 如果print(y) 看起来像{"High": [...], "Medium": [...]},那么你也可以使用print(y["High"]
    • 高看起来像这样:"RiskLevel": "High",
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2017-08-09
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多