【问题标题】:Deserializing JSON into python Class / Object将 JSON 反序列化为 python 类/对象
【发布时间】:2018-07-24 05:34:07
【问题描述】:

我对 python 还很陌生,需要帮助获取 json 文件并合并 将它放入一个类中的 init 中以供使用,但我收到以下错误并且不明白为什么。我之前构建了几个类,这看起来是一样的。

AttributeError: 'dict' object has no attribute 'zipcode'

我有一个名为 config.json 的单独 json 文件,我更改了其中的一些信息(即位置和 api 密钥),但除此之外,这就是我正在使用的。

config.json:

{
    "unit_system":"metric",

    "location_information":{
        "country_code":"US",
        "country_name":"United States",
        "city":"New York City",
        "state":"New York",
        "postal":10001
    },

    "api_keys":{
        "weather_api_key":"97a484e1039b7a0779b59f2e57e597a3"
    }
}

weather.py

class weather:
    """weather retrieving app"""

    def __init__(self, data):
        """initialize attributes for weather app"""

        self.unit_system = data['unit_system']
        #unit system

        self.country_code = data['location_information']['country_code']
        self.zipcode = data['location_information']['postal']
        #location information

        self.api_key = data['api_keys']['weather_api_key']
        #api key informaation

    def get_update(self):

        threading.Timer(5.0, w.get_update).start()
        #runs get_update every 5 seconds

        #get weather information
        weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \
        + str(self.zipcode) + ',' \
        + self.country_code + '&appid=' \
        + self.api_key

        weather_request = requests.get(weather_url)
        weather_data = weather_request.json()
        temp_k = float(weather_data['main']['temp'])

        #determine unit system conversions
        if self.unit_system == 'english':

            temp = (temp_k - 273.15) * 1.8 + 32

        elif self.unit_system == 'metric':

            temp = temp_k - 273.15

        print(temp)
        #return(temp)

import threading
import requests
import json

with open('config.json') as config_file:
    config = json.load(config_file)

w = weather(config)

w.get_update()

【问题讨论】:

  • 您必须通过传递data 来构造weather 对象,例如w = weather(config)。然后您可以拨打w.get_update()。您正在做的是调用weather.update 方法并要求它使用config 作为weather 实例,但事实并非如此,因此您会出错。
  • @abarnert,感谢您的回复,这是我的一个快速疏忽。我已经更新了代码,所以它可以正常工作并每 5 秒拉一次更新。

标签: python json class object


【解决方案1】:

删除最后一行并将这些行放在底部。第一行创建了一个名为 weather_obj 的类天气实例。然后您可以使用 weather_obj 调用 get_update

weather_obj = weather(config)
weather_obj.get_update()

【讨论】:

    【解决方案2】:

    您提供的 scipt 似乎正在运行。 a screenshot of my output(s)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多