首页 > 解决方案 > 在单独的函数中使用相同的键值使用 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,

标签: pythonjsonfunctiondictionary

解决方案


推荐阅读