简体   繁体   中英

TypeError: string indices must be integers when reading data from json

I am trying to pull the title out of my .json file. Ended up with an error. Wondering if any of you could assist me and point out what I am doing wrong.

I have the problem code down below with the error code.

title = ('0')
for eq_data in all_eq_data:
    title = (eq_data['metadata']['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]

Below is a snippet of the data I am trying to pull and how it looks like


 "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

People are getting confused. Ill post the rest of the code below


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'])


#all_eq_info = all_eq_data

title = ('0')
for eq_data in all_eq_data:
    title = (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')

Currently, you are accessing the raw JSON string, you have to parse the string into an object before you can reference it. In Python that means using the json module. The easiest way of doing this is using json.loads() .

Example:

import json

json_string = '{"title": "some title", "data": "some data"}'

#should return a dictionary with "some title" as "title" and "some data" as "data"
data = json.loads(json_string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM