Python读取JSON遇TypeError:string indices must be integers 求助
JSON字段提取错误:TypeError: string indices must be integers 解决方法
问题重现
尝试从JSON文件提取title字段时触发如下错误:
Traceback (most recent call last): File "C:\Users\2\Desktop\python_work\Chapter 16 - 20\Chapter 16\16.7 Automated Title.py", line 29, in <module> title = (eq_data['metadata']['title']) TypeError: string indices must be integers [Finished in 661ms]
问题代码片段:
title = ('0') for eq_data in all_eq_data: title = (eq_data['metadata']['title'])
目标JSON数据结构(关键片段):
"type": "FeatureCollection", "metadata": { "generated": 1550361461000, "url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson", "title": "USGS Magnitude 1.0+ Earthquakes, Past Day", "status": 200, "api": "1.7.0", "count": 158 }
错误原因
all_eq_data是通过json.load(f)加载得到的字典对象,直接遍历字典时,循环变量eq_data会依次取到字典的键名(字符串类型),比如'type'、'metadata'、'features'。此时尝试用eq_data['metadata']去访问,本质是用字符串索引字符串,自然会触发string indices must be integers错误。
而且title字段本身就在all_eq_data['metadata']下,完全不需要循环遍历。
解决方案
删除多余的for循环,直接通过字典键路径获取title:
title = all_eq_data['metadata']['title']
修正后的完整代码
import json from plotly.graph_objs import Scattergeo, Layout from plotly import offline # Explore the structure of the data. filename = 'data/eq_data_30_day_m1.json' with open(filename) as f: all_eq_data = json.load(f) all_eq_dicts = all_eq_data['features'] mags, lons, lats, hover_texts = [], [], [], [] for eq_dict in all_eq_dicts: mags.append(eq_dict['properties']['mag']) lons.append(eq_dict['geometry']['coordinates'][0]) lats.append(eq_dict['geometry']['coordinates'][1]) hover_texts.append(eq_dict['properties']['title']) # 直接获取title,无需循环 title = all_eq_data['metadata']['title'] # Map the earthquake. data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [3*mag for mag in mags], 'color': mags, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': {'title': 'Magnitude'}, } }] my_layout = Layout(title=title) fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='auto_global_earthquakes.html')
内容的提问来源于stack exchange,提问作者KiddoPL
相关产品推荐
相关产品推荐

