python - 在单独的函数中使用相同的键值使用 python 解析 JSON 时出现键错误
问题描述
我收到“数据”的关键错误,据我所知,这是因为我在以下两个函数中都使用了它:
无论第一个调用的函数成功返回“平均值”值,但调用的第二个函数始终返回 KeyError:“数据”。我试过先打电话给每个人,这在每种情况下都会发生。
import requests
import json
max_age = 6
data_points = 30
while True:
postcode = input('Enter the postcode: ')
if len(postcode) < 5:
print("Postcode is at least 5 characters. Try again.")
elif len(postcode) > 8:
print("Postcode is no more than 8 characters. Try again.")
else:
print(" ")
break
building_type = input(f'Enter type [flat, terraced_house, semi_detached_house, detached_house]: ')
beds = input(f'Enter number of bedrooms: ')
max_age = 6
data_points = 30
def asking_rent():
asking_rent_url = f"https://api.propertydata.co.uk/rents?key=xxxxx&postcode={postcode}&bedrooms={beds}&property_type={building_type}&points={data_points}"
r2 = requests.get(asking_rent_url)
json_data2 = json.loads(r2.text)
asking_rent_value = json_data2['data']['long_let']['average']
print(f"Asking Rent: £{asking_rent_value}")
def sold_price_per_sqft():
sold_price_url = f"https://api.propertydata.co.uk/sold-prices-per-sqf?key=xxxxx&postcode={postcode}&max_age={max_age}&type={building_type}&points={data_points}"
r3 = requests.get(sold_price_url)
json_data3 = json.loads(r3.text)
sold_price_value = json_data3['data']['average']
print(f"Sold Price Per sqft: £{sold_price_value}")
asking_rent()
sold_price_per_sqft()
否则如何从以下两个 JSON 中提取“平均值”值,或者是否有更合适的方法来成功返回这两个函数?
json_data2:
{
"status": "success",
"postcode": "TW3 1NE",
"postcode_type": "full",
"url": "https://propertydata.co.uk/draw?input=TW3+1NE",
"bedrooms": 2,
"data": {
"long_let": {
"points_analysed": 30,
"radius": "0.38",
"unit": "gbp_per_week",
"average": 319,
json_data3:
{
"status": "success",
"postcode": "TW3 1NE",
"postcode_type": "full",
"url": "https://propertydata.co.uk/draw?input=TW3+1NE",
"type": "flat",
"max_age": 6,
"data": {
"points_analysed": 30,
"radius": "1.00",
"date_earliest": "2019-10-25",
"date_latest": "2020-02-07",
"average": 466,
解决方案
推荐阅读
- continuous-integration - 我如何确保为不同的 git 分支提供不同的 Travis CI 工作流程
- r - R中嵌套数据结构中各种元素求和的函数的问题
- java - Micronaut 为 Pact 测试设置 EmbeddedServer
- c# - S3 by Scaleway 通过 Amazon.S3 nuget 包
- android-studio - 在 TeamCity 上通过 gradle build step 构建 android 项目时如何修复“Aapt2InternalException:AAPT2”错误?
- chef-infra - 通过配置定义 Chef Kitchen 实例的自定义结构?
- android - 将像素从一种密度转换为另一种
- java - Junit 测试断言错误预期为 3,但附带 0
- node-modules - 错误:使用离子服务时缺少绑定
- php - strtotime PHP的奇怪响应