A websocket connection to SeismicPortal is sending me data about earthquakes packed in a JSON object which I get as a multi-line string, e.g.:
{
"action": "create",
"data": {
"geometry": {
"coordinates": [
-95.12,
16.52,
-52.0
],
"type": "Point"
},
"id": "20180303_0000046",
"properties": {
"auth": "UNM",
"depth": 52.0,
"evtype": "ke",
"flynn_region": "OAXACA, MEXICO",
"lastupdate": "2018-03-03T10:26:00.0Z",
"lat": 16.52,
"lon": -95.12,
"mag": 4.0,
"magtype": "m",
"source_catalog": "EMSC-RTS",
"source_id": "652127",
"time": "2018-03-03T07:09:05.0Z",
"unid": "20180303_0000046"
},
"type": "Feature"
}
}
I want to have the data from the string converted to a python object.
As you see in the JSON data, there is a lot of nesting. As I was defining the classes and their embeddedness to build a on object of a structure which would hold all the data from the JSON I was thinking maybe there is some magic Python function jsonStringToObject which would tailor a class and all subclasses needed to hold all the data in the JSON and make an instance of it.
Let's have the raw JSON string in the variable rawData:
rawData = """{"action":"create","data":{"geometry": {"type": "Point","coordinates": [... """
Right now I have to do this:
>>> import json
>>> quake = json.loads(rawData)
>>> quake['data']['properties']['flynn_region']
"OXACA_MEXICO"
but the syntax is crammed with brackets and apostrophes.
I wish I could just access the data like this:
>>> import json
>>> quake = jsonStringToObject(rawData)
>>> quake.data.properties.flynn_region
"OXACA_MEXICO"