如何在python中将未加载的JSON数据放入变量中

2024-10-02 10:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

import requests
import json
import csv

# These our are demo API keys, you can use them!
#location = ""
api_key = 'simplyrets'
api_secret = 'simplyrets'
#api_url = 'https://api.simplyrets.com/properties?q=%s&limit=1' % (location)
api_url = 'https://api.simplyrets.com/properties'

response = requests.get(api_url, auth=(api_key, api_secret))
response.raise_for_status()
houseData = json.loads(response.text)

#different parameters we need to know
p = houseData['property']
roof = p["roof"]
cooling = p["cooling"]
style = p["style"]
area = p["area"]
bathsFull = p["bathsFull"]
bathsHalf = p["bathsHalf"]

这是我正在使用的代码片段,尝试从API提供的JSON中获取信息,并将它们放入可以实际使用的变量中。在

我以为当你用json.loads()加载它时,它会变成一个字典。在

但它告诉我我不能做p = houseData['property'],因为“list indices must be integers, not str”。在

我错了,houseData应该是字典吗?


Tags: keyhttpsimportcomapijsonurlsecret
3条回答

来自https://docs.python.org/2/library/json.html

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

If s is a str instance and is encoded with an ASCII based encoding other than UTF-8 (e.g. latin-1), then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to unicode first.

The other arguments have the same meaning as in load().

如果JSON从最外层的数组开始,它将是一个数组。如果您的JSON最外层是一个关联数组,那么请发布您的JSON,我们可以进一步研究它。在

返回了数百个属性,它们都在一个列表中。在

您需要指定所需的属性,因此对于第一个属性:

p = houseData[0]['property']

问题是json.loads()不一定返回字典。如果JSON的外部容器是一个列表,那么json.loads()将返回一个列表,其中的元素可以是列表或字典。尝试遍历json.loads()返回的列表。您要查找的字典可能只是json.loads()[0]或其他元素。在

相关问题 更多 >

    热门问题