gpt4 book ai didi

python - jsonResponse = r.json() 名称错误 : name 'r' is not defined

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:31 26 4
gpt4 key购买 nike

我正在尝试从 EPL Premier League Fantasy Football 官方网站提取一些数据,但在 jsonResponse 方面遇到问题。

尝试安装 simplejson pip install simplejson

不确定还可以尝试什么,请参阅我的代码:

import pandas as pd
import json
import requests
from pandas.io.json import json_normalize

# Define a function to get info from the FPL API and save to the specified file_path
# It might be a good idea to navigate to the link in a browser to get an idea of what the data looks like

def get_json(file_path): r = requests.get('https://fantasy.premierleague.com/api/bootstrap-static/')
jsonResponse = r.json()
with open(file_path, 'w') as outfile: json.dump(jsonResponse, outfile)

# Run the function and choose where to save the json file
get_json('C:\Ste Files\Python\test\fpl.json')

# Open the json file and print a list of the keys

with open('C:\Ste Files\Python\test\fpl.json') as json_data: d = json.load(json_data)
print(list(d.keys()))

我希望将文件写入代码中的路径。但我收到以下错误:

(base) C:\Ste File\Python\test>python ste_test.py
Traceback (most recent call last):
File "ste_test.py", line 10, in <module>
jsonResponse = r.json()
NameError: name 'r' is not defined

最佳答案

indentation可能会欺骗你:

更改您的代码:

def get_json(file_path): r = requests.get('https://fantasy.premierleague.com/api/bootstrap-static/')
jsonResponse = r.json()
with open(file_path, 'w') as outfile: json.dump(jsonResponse, outfile)

与:

def get_json(file_path):
r = requests.get('https://fantasy.premierleague.com/api/bootstrap-static/')
jsonResponse = r.json()
with open(file_path, 'w') as outfile:
json.dump(jsonResponse, outfile)

或者:

import pandas as pd
import json
import requests
from pandas.io.json import json_normalize
import os

dir_path = os.getcwd()

json_path = os.path.join(dir_path, 'fpl.json')


# Define a function to get info from the FPL API and save to the specified file_path
# It might be a good idea to navigate to the link in a browser to get an idea of what the data looks like

def get_json(file_path):
r = requests.get('https://fantasy.premierleague.com/api/bootstrap-static/')
jsonResponse = r.json()
with open(file_path, 'w') as outfile:
json.dump(jsonResponse, outfile)

# Run the function and choose where to save the json file
get_json(json_path)

# Open the json file and print a list of the keys

with open(json_path) as json_data:
d = json.load(json_data)

print(list(d.keys()))
# output: ['events', 'game_settings', 'phases', 'teams', 'total_players', 'elements', 'element_stats', 'element_types']

关于python - jsonResponse = r.json() 名称错误 : name 'r' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57399147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com