类型错误:字符串索引必须是整数(Python)

时间:2020-12-28 12:28:43

标签: python json mongodb

我在尝试使用以下代码迭代 JSON 时收到 TypeError: string indices must be integers。我试图在其他多个线程中找到答案,但没有运气。

这是我的 JSON 的开始:

    '?xml': {
    '@version': '1.0',
    '@encoding': 'ISO-8859-1'
},
'scores': {
    '@sport': 'soccer',
    '@updated': '28.12.2020 04:49:21',
    'category': [{
        '@name': 'Africa: Caf Champions League - Qualification',
        '@gid': '19297',
        '@id': '1513',
        '@file_group': 'africa',
        '@iscup': 'False',
        'matches': {
            '@date': 'Dec 28',
            '@formatted_date': '28.12.2020',
            'match': {
                '@status': '19:45',
                '@timer': '',
                '@date': 'Dec 28',
                '@formatted_date': '28.12.2020',
                '@time': '19:45',
                '@commentary_available': '1513',
                '@venue': '',
                '@v': '0',
                '@static_id': '2938748',
                '@fix_id': '3445943',
                '@id': '3792777',
                'localteam': {
                    '@name': 'MC Alger',
                    '@goals': '?',
                    '@id': '5784'
                },
                'visitorteam': {
                    '@name': 'Sfaxien',
                    '@goals': '?',
                    '@id': '16927'
                },
                'events': None,

这是我正在运行的 Python 代码:

import urllib.request, json, random, pymongo
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client["gameDB"]
collection = db["players"]

with urllib.request.urlopen("https://www.myjsonfile.com") as url:
    data = json.loads(url.read().decode())
    #print(data)

league_id = 0
league_name = ''
match_id = 0
match_name = ''

for league in data['scores']['category']:
    league_id = league['@id']
    league_name = league['@name']

    
    
    
    for match in league['matches']['match']:
        
        match_id = match['@static_id']
        match_name = match['localteam']['@name']

        print({"{} {} {} {}".format(league_id, league_name, match_id, match_name)})

这是我得到的错误:

    Traceback (most recent call last):
  File "/Users/testScript.py", line 30, in <module>
    match_id = match['@static_id']
TypeError: string indices must be integers

我感到困惑的原因是它适用于某些代码但不适用于其他代码,并且代码看起来相同:

'@static_id': '2938748',

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

仔细看看你在这里实际循环的内容:

for match in league['matches']['match']:
    match_id = match['@static_id']
    match_name = match['localteam']['@name']

match 在这种情况下是 match dict 的 keys,即 '@status''@timer' 等,它们是 < em>字符串。您可以在 Pyhton 中使用 idices 访问字符串的字符,即 'example'[1] # 'x'。这就是错误消息的来源。你想要的是这个:

match = league['matches']['match']:
match_id = match['@static_id']
match_name = match['localteam']['@name']

答案 1 :(得分:0)

for match in league['matches']['match']:
    
    match_id = match['@static_id']
    match_name = match['localteam']['@name']

您正在像列表一样迭代字典(匹配)。你需要像字典一样迭代它:

for key, value in data.items():
    print(key, value)