You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析词典API带方括号的JSON数据遇索引问题求助

解析词典API返回的JSON数组时的索引错误解决方法

问题背景

从英语词典API获取的JSON数据外层是方括号包裹的数组,解析时直接用data["meanings"]会触发错误:list indices must be integers or slices, not str,添加[0](即data[0]["meanings"])后能正常访问,但不清楚原因,同时内层嵌套的meanings、definitions也存在类似问题,想知道正确处理方式是加索引还是移除方括号。

核心原因

API返回的JSON外层是数组结构(方括号[]标识),数组在Python等语言中只能通过整数索引(比如[0]取第一个元素)或切片访问,不能直接用字符串键(比如"meanings")取值。而数组里的每个元素才是包含word、meanings等属性的字典对象,只有字典才能用字符串键访问属性。

正确处理方式

1. 不要手动移除JSON中的方括号

方括号是API返回的合法结构,它表示可能返回多个结果(比如同形异义词的情况),手动修改会破坏数据结构,后续如果API返回多个结果时会直接出错。

2. 针对数组结构做对应处理

  • 如果确定API只会返回单个单词的结果:直接用[0]取出数组中的第一个字典对象,再访问内层属性
  • 如果API可能返回多个结果:遍历数组,逐个处理每个单词对象

3. 内层嵌套数据的处理

meanings、definitions本身也都是数组(比如一个单词可能有名词、动词等多个词义类别,每个词义类别下有多个定义),所以同样需要用索引或循环来访问:

代码示例(Python)

import json

# 模拟API返回的JSON数据
api_response = '''
[
    {
        "word": "apple",
        "meanings": [
            {
                "partOfSpeech": "noun",
                "definitions": [
                    {
                        "definition": "A common, round fruit produced by the tree Malus domestica, cultivated in temperate climates.",
                        "example": "She ate an apple for breakfast."
                    },
                    {
                        "definition": "The tree bearing such fruit.",
                        "example": "We planted three apple trees in the backyard."
                    }
                ]
            },
            {
                "partOfSpeech": "verb",
                "definitions": [
                    {
                        "definition": "To make or become apple-shaped.",
                        "example": "The dough appled as it baked."
                    }
                ]
            }
        ]
    }
]
'''

# 解析JSON
data = json.loads(api_response)

# 取出第一个单词对象(如果只有一个结果)
word_info = data[0]

# 处理meanings数组
for meaning in word_info["meanings"]:
    print(f"\n词性:{meaning['partOfSpeech']}")
    # 处理definitions数组
    for idx, definition in enumerate(meaning["definitions"], 1):
        print(f"定义{idx}:{definition['definition']}")
        if "example" in definition:
            print(f"示例{idx}:{definition['example']}")

总结

所有被方括号包裹的部分都是数组,必须先用整数索引或循环遍历取出元素,再用字符串键访问字典属性;不要手动修改API返回的JSON结构,保持原始数据的完整性才能兼容各种返回情况。

内容的提问来源于stack exchange,提问作者Stephen Frosty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:32:51