使用Python将JSON转换为文本文件

2024-04-25 07:14:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找解决这个问题的办法,但我没有找到一个我能理解的办法。我是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)

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


Tags: importjsonhttp消息getis错误not
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对象。你知道吗

你不需要把它转换成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)

相关问题 更多 >