【问题标题】:JSON to text file using Python使用 Python 将 JSON 转换为文本文件
【发布时间】:2016-06-27 19:26:53
【问题描述】:

我已经搜索了有关此问题的解决方案,但没有找到我可以理解的解决方案。我是 Python 新手,需要基本帮助来理解为什么会收到错误消息:TypeError: is not JSON serializable。

import requests
import json

r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005")

with open("C:\...MyPath...\Output.txt", "w") as outfile:
    json.dumps(r, outfile)

这是我正在测试的简单代码。我很感激帮助。

【问题讨论】:

  • r 不是 JSON 对象;你不能dumps 不是 json 的东西。但是,您可以先将 bls 字符串解析为 JSON 对象,然后将其转储。不过,我认为这没有多大意义。
  • 你还需要在 with 块中缩进你的 json.dumps

标签: python json python-requests


【解决方案1】:

您无需将其转换为 json。将其保留为文本即可。

import requests

r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005")

with open("C:\Users\mhoward2\Documents\Python Scripts\Output.txt", "w") as outfile:
    outfile.write(r.text)

【讨论】:

  • 非常感谢> 现在我的硬盘上有一些 JSON。多年来,我从 stackoverflow 中学到了很多……VBA……SQL……现在是 Python。这是我不得不问的第一个问题。
  • 很高兴我能帮上忙 :)
【解决方案2】:

你需要调用.json()dump或者直接写内容:

r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005")

with open("C:\Users\mhoward2\Documents\Python Scripts\Output.txt", "w") as outfile:
     outfile.write(r.content)

你现在要写的是:

 <Response [200]>

这是一个requests.models.Response 对象。

【讨论】:

  • content 允许您以字节形式访问响应,因此对open 的调用可能应该有wb 而不仅仅是w
  • @iliacholy,不在 python2 中。
  • 什么意思? (不是说你错了,只是好奇)
  • bytes 是 python2 中 str 的别名,type(r.content) -&gt; str,一般情况下你应该在请求中使用 .content 并让它处理编码。 Python 3 显然是另一回事
猜你喜欢
  • 2022-01-17
  • 2020-06-12
  • 2019-03-25
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多