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

Python遍历JSON并添加新字段遇IndexError报错求助

问题解决指南

1. 先搞定IndexError错误

你用range(3000)硬写循环次数,但你的data['features']列表里的元素数量大概率不到3000,硬按索引访问肯定会越界。直接遍历列表里的每个元素就行,不用手动数索引:

for feature in data['features']:
    attributes = feature['attributes']
    # 后面操作都用这个attributes变量

2. 别替换整个字典,要新增字段

你之前的代码把attributes整个换成只有url的新字典,原来的步道信息全丢了。正确做法是在原字典里加个新字段:

attributes['url'] = urlvar  # 这才是新增,不是替换

3. 防一手缺失website的情况

有些步道可能没填官网,直接访问attributes['website']会触发KeyError,加个判断跳过或者设默认值:

if 'website' in attributes and attributes['website'].strip():
    # 有有效官网才生成链接
    urlvar = f'<a href="{attributes["website"]}">{attributes["website"]}</a>'
    attributes['url'] = urlvar
else:
    attributes['url'] = '无官方网站'  # 没官网就显示提示

4. 别忘了把修改写回文件

你之前只改了内存里的数据,没保存到文件,最后要加写入步骤:

with open('data/querycopy_updated.json', 'w', encoding='utf8') as outfile:
    json.dump(data, outfile, ensure_ascii=False, indent=2)

完整可运行代码

import json

def main():
    # 读取原JSON文件
    with open('data/querycopy.json', 'r', encoding="utf8") as jsonFile:
        data = json.load(jsonFile)
    
    # 遍历每个步道数据
    for feature in data['features']:
        attributes = feature['attributes']
        # 检查是否有有效官网链接
        if 'website' in attributes and attributes['website'].strip():
            url = attributes['website'].strip()
            # 生成带链接文本的HTML标签(你也可以换成步道名称)
            urlvar = f'<a href="{url}">{url}</a>'
            attributes['url'] = urlvar
        else:
            attributes['url'] = '无官方网站'
    
    # 写入修改后的新文件(别直接覆盖原文件,留个备份)
    with open('data/querycopy_updated.json', 'w', encoding='utf8') as outfile:
        json.dump(data, outfile, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    main()

额外小提示

  • 建议写入新文件而不是覆盖原文件,避免操作失误丢数据
  • 如果想让链接显示步道名称(不是URL),可以把{url}换成对应的字段,比如attributes["trail_name"](具体字段名看你的JSON结构)
  • 要是遇到不带http的URL,比如www.example.com,可以加个判断补全:
    if not url.startswith(('http://', 'https://')):
        url = f'https://{url}'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:12:54