gpt4 book ai didi

python - 如何指定请求以 JSON 格式返回数据?

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:47 26 4
gpt4 key购买 nike

我是 Python 请求模块的新手,我正在尝试从 Lichess.org API 中导出用户的游戏数据。 (国际象棋网站)。

这是我的代码:

import requests, json

url = "https://www.lichess.org/api/games/user/mbellm"

r = requests.get(url, params={"max":2, "analysed":"true", "clocks":"true", "evals":"true", "opening":"true"})
r_text = r.content.decode("utf-8"))
print(r_text)
#data = json.loads(r_text)

r_text 中收到的输出似乎不是 JSON/NDJSON 格式,而是 PGN 格式(一种国际象棋符号)。在我链接到上面的 API 文档的部分中,它声明您可以指定是接收 JSON 格式的数据还是 PGN 格式的数据,但我没有看到任何地方说明如何选择接收数据的格式。

如何设置我的代码以返回 JSON/NDJSON 格式的提取数据?

print(r_text) 的当前输出:

[Event "Rated Bullet game"]
[Site "https://lichess.org/IqlbjkHX"]
[Date "2019.01.13"]
[Round "-"]
[White "mbellm"]
[Black "Ruediruempel"]
[Result "0-1"]
[UTCDate "2019.01.13"]
[UTCTime "22:45:48"]
[WhiteElo "1097"]
[BlackElo "1202"]
[WhiteRatingDiff "-8"]
[BlackRatingDiff "+7"]
[Variant "Standard"]
[TimeControl "60+0"]
[ECO "C50"]
[Termination "Normal"]

1. e4 e5 2. Nf3 Nf6 3. Bc4 Nc6 4. d3 Bc5 5. Nc3 Nd4 6. O-O O-O 7. Nxd4 Bxd4 8. Nd5 Nxd5 9. Bxd5 c6 10. c3 cxd5 11. cxd4 dxe4 12. Qg4 exd3 13. dxe5 d6 14. Bd2 Bxg4 15. exd6 Qxd6 16. f3 Bf5 17. Rad1 h6 18. a3 Bh7 19. Bb4 Qd4+ 20. Kh1 Qxb2 21. Rxd3 Bxd3 22. Rc1 Qxc1+ 23. Be1 Qxe1# 0-1


[Event "Rated Classical game"]
[Site "https://lichess.org/sgNWdvkn"]
[Date "2019.01.13"]
[Round "-"]
[White "Stalingrad_1"]
[Black "mbellm"]
[Result "1-0"]
[UTCDate "2019.01.13"]
[UTCTime "04:15:39"]
[WhiteElo "1656"]
[BlackElo "1732"]
[WhiteRatingDiff "+13"]
[BlackRatingDiff "-13"]
[Variant "Standard"]
[TimeControl "900+15"]
[ECO "D00"]
[Termination "Normal"]

1. d4 d5 2. e3 Nf6 3. c4 c6 4. Qb3 Nbd7 5. Nc3 Nb6 6. cxd5 Nfxd5 7. Nxd5 cxd5 8. Bb5+ Bd7 9. Nf3 e6 10. Bxd7+ Qxd7 11. Ne5 Qc7 12. Bd2 Bd6 13. Rc1 Qe7 14. Qb5+ Kf8 15. f4 Bxe5 16. dxe5 Nc4 17. Bb4 1-0

最佳答案

看起来这个端点的默认格式是 application/x-chess-pgn,但是 application/x-ndjson 也是可用的。 (这来自API docs)

要告诉 API 您需要 application/x-ndjson,您可以使用 Accept header 。

例如:

import requests, json

url = "https://www.lichess.org/api/games/user/mbellm"

r = requests.get(
url,
params={"max":2, "analysed":"true", "clocks":"true", "evals":"true", "opening":"true"},
headers={"Accept": "application/x-ndjson"}
)
r_text = r.content.decode("utf-8")
print(r_text)

r_text 示例:

{"id":"0ngCNyCN","rated":true,"variant":"standard","speed":"classical","perf":"classical","createdAt":1547495368806,"lastMoveAt":1547498443462,"status":"resign","players":{"white":{"user":{"id":"mbellm","name":"mbellm"},"rating":1715,"ratingDiff":-9,"analys

编辑

由于此 API 的响应是 ndjson 或 Newline Delimed JSON,调用 json.loads 将无法在响应数据上正常工作。您可以在换行符 "\n" 上拆分响应数据,然后在每个子字符串上调用 json.loads。请注意,响应以 "\n" 结尾,因此请确保不要在最后一个子字符串上调用 json.loads

这是一个例子:

games = [json.loads(s) for s in r_text.split("\n")[:-1]]

关于python - 如何指定请求以 JSON 格式返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191861/

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