使用Python将JSON转换为文本文件
我已经就这个问题寻找了一个解决方案,但还没有找到一个我能理解的解决方案。我是Python新手,需要一些基本的帮助来理解为什么我会收到错误消息:TypeError:is not JSON serializable使用Python将JSON转换为文本文件,python,json,python-requests,Python,Json,Python Requests,我已经就这个问题寻找了一个解决方案,但还没有找到一个我能理解的解决方案。我是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..
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)
这是我正在测试的简单代码。我感谢你的帮助 您不需要将其转换为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()和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
对象。r
不是JSON对象;您不能转储非json的内容。但是,您可以先将bls字符串解析为JSON对象,然后转储它。不过,我觉得这没什么意义。你还需要缩进你的json。块中的dumpscontent
允许你以字节的形式访问响应,因此对open
的调用应该有wb
而不是w
@iliachory,而不是python2。你是什么意思?(并不是说你错了,只是好奇)bytes是python2中str的别名,type(r.content)->str
,通常你应该在请求中使用.content,并让它处理编码。Python3显然是另一个故事非常感谢>我现在硬盘上有一些JSON。多年来,我从stackoverflow中学到了很多…VBA…SQL…现在是Python。这是我不得不问的第一个问题。很高兴我能帮上忙:)