类型错误:预期的 str、bytes 或 os.PathLike 对象,而不是 dict

问题描述

这是我的代码

from os import rename,write
import requests
import json

url = "https://api.github.com/search/users?q=%7Bquery%7D%7B&page,per_page,sort,order%7D"
data = requests.get(url).json()
print(data)

outfile = open("C:/Users/vladi/Desktop/json files Vlad/file structure first attemp.json","r")
json_object = json.load(outfile)

with open(data,'w') as endfile:
    endfile.write(json_object)
    print(endfile)

我想调用 API 请求。 我想从这个 URL 获取数据:https://api.github.com/search/users?q=%7Bquery%7D%7B&page,order%7D, 并用我自己的数据重写它,这是我名为 file structure first attemp.json文件 并使用我自己的数据更新此 URL。

解决方法

import requests

url = "https://api.github.com/search/usersq=%7Bquery%7D%7B&page,per_page,sort,order%7D"

data = requests.get(url)

with open(data,'w') as endfile:
    endfile.write(data.text)
  • json.loads() 返回一个无法写入文件的 Python 字典。只需编写从 URL 返回的字符串。

  • response.json() 是一个内置功能,requests 使用它来加载从 URL 返回的 JSON。所以你加载了两次 JSON。