【问题标题】:Understanding json dump in python 3.5了解python 3.5中的json转储
【发布时间】:2017-01-14 20:35:05
【问题描述】:

我不精通 json 或 python。我正在创建一个简单的脚本来获取本地当前温度并将其放入 txt 文件中(因为我假设我可以让 python 在稍后的步骤中读取 txt 文件)。到目前为止,我已经设法使用 json 数据创建了 txt 文件,但我只想将我想要的相关数据写入 txt 文件。

import requests
import json
key = [KEY]
while 1:
    res = requests.get('http://api.wunderground.com/api/' + key + '/geolookup/conditions/q/[STATE]/[ZIP].json')
json_string = res.json()
with open("weather_result.txt","w") as fp:
    json.dumps(json_string, fp)
temperature_string = parsed_json['current_observation']['temp_f']
print (temperature_string)

我哪里错了?我似乎无法理解这个 json 转储的字符串或字典。

感谢您的帮助。

【问题讨论】:

  • 我看不懂你的代码。 while 1? parsed_json 定义在哪里?
  • 你熟悉fp.write('string here')吗?
  • 您还没有告诉我们出了什么问题或文件中的内容。看起来您有一个无限循环,只是一遍又一遍地执行请求。文本文件是否应该是 parsed_json['current_observation']['temp_f'] 中内容的 json 转储。你叫它temperture_string...它只是一个字符串吗?您真的要编写字符串的 json 序列化还是只编写字符串?是否要多次写入此数据(然后以换行符终止,以便将它们区分开来)?
  • 在阅读了这些 cmets 之后,我意识到我的错误,“parsed_json”没有被定义,因为我打算使用“json_string”。那个和“while 1:”都是我没有意识到的旧代码的残余。我想做的就是获取当前温度。我从使用 json 开始,因为我正在学习一个教程,然后继续前进。

标签: python json api


【解决方案1】:

我在您的代码中发现了 2 个问题。

  1. 为了保存将结果保存到文件中。将json.dumps 更改为json.dump

示例: with open("weather_result.txt","w") as fp: json.dump(json_string, fp)

  1. 从未定义变量parsed_json。也许您应该在代码中将parsed_json 分配给res

【讨论】:

  • 我的例子中的错字。意思是 json.dump,而不是 json.dumps
【解决方案2】:

由于循环中只有一个语句,因此您的代码将在紧密循环中尽可能快地请求该页面。您需要在循环内移动剩余的代码。然后,因为你想要的只是温度,所以跳过写 json 并只写那部分。在那里睡一觉,以适应地下的天气,你应该很高兴去。

请注意,由于此代码每次要使用文件时都会休眠并重新打开文件。您可以通过将with 移到while 之外来保持文件打开(并可能在写入后添加fp.flush(),以便其他人可以读取当前数据)。虽然它是一个权衡。这样,您可以在另一个 shell 中移动或删除文件,这个程序将开始填充一个新的。

import requests
import time

key = [KEY]
while 1:
    res = requests.get('http://api.wunderground.com/api/' + key + '/geolookup/conditions/q/[STATE]/[ZIP].json')
    with open("weather_result.txt","a") as fp:
        temperature_string = res.json()['current_observation']['temp_f']
        print(temperature_string)
        fp.write('{}\n', temperature_string)
    time.sleep(5*60)

【讨论】:

    猜你喜欢
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2013-06-25
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多