jsonResponse=r.json()NameError:未定义名称“r”

2024-09-29 02:23:06 发布

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

我正试图从EPL英超梦幻足球官方网站上获取一些数据,但遇到了问题。你知道吗

尝试安装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

Tags: andthetopath代码testimportjson
1条回答
网友
1楼 · 发布于 2024-09-29 02:23:06

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']

相关问题 更多 >