簡體   English   中英

試圖從 JSON URL 中提取數據到 Pandas

[英]Trying to extract data from JSON URL into Pandas

我正在嘗試從 JSON URL 中提取數據到 pandas 但這個文件有多個列表和字典的“層”,我似乎無法導航。

import json
from urllib.request import urlopen

with urlopen('https://statdata.pgatour.com/r/010/2020/player_stats.json') as response:
    source = response.read()

data = json.loads(source)

for item in data['tournament']['players']:
    pid = item['pid']
    statId = item['stats']['statId']
    name = item['stats']['name']
    tValue = item['stats']['tValue']
    print(pid, statId, name, tValue)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-84-eadd8bdb34cb> in <module>
      1 for item in data['tournament']['players']:
      2     player_id = item['pid']
----> 3     stat_id = item['stats']['statId']
      4     stat_name = item['stats']['name']
      5     stat_value = item['stats']['tValue']

TypeError: list indices must be integers or slices, not str

我試圖到達的 output 就像:-

在此處輸入圖像描述

你少了一層。

為了簡化數據,我們嘗試訪問:

"stats": [{
    "statId":"106",
    "name":"Eagles",
    "tValue":"0",
}]

'stats' 的數據以[{開頭。 這是數組中的字典。

認為這應該有效:

for item in data['tournament']['players']:
    pid = item['pid']
    for stat in item['stats']:
        statId = stat['statId']
        name = stat['name']
        tValue = stat['tValue']
        print(pid, statId, name, tValue)

要閱讀有關詞典的更多信息: https://realpython.com/iterate-through-dictionary-python/

正如前面的答案所暗示的, statsstat項目的列表。 這將向您展示發生了什么,並發現任何其他問題:

import json
from urllib.request import urlopen

with urlopen('https://statdata.pgatour.com/r/010/2020/player_stats.json') as response:
    source = response.read()

data = json.loads(source)

for item in data['tournament']['players']:
    try:
        pid = item['pid']
        stats = item['stats']
        for stat in stats:
            statId = stat['statId']
            name = stat['name']
            tValue = stat['tValue']
            print(pid, statId, name, tValue)
     except Exception as e:
        print(e)
        print(item)
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM