从Json字符串创建Python对象 [英] Creating a Python object from a Json string
问题描述
与 SeismicPortal 的Websocket连接向我发送了有关打包在JSON对象中的地震数据我得到的是多行字符串,例如:
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"
}
}
我想将字符串中的数据转换为python对象.
I want to have the data from the string converted to a python object.
正如您在JSON数据中看到的,有很多嵌套.当我定义类和它们的嵌入性以构建一个结构的on对象时,该对象将保存来自JSON的所有数据,我在想,也许有一些神奇的Python函数 jsonStringToObject 可以定制一个类并所有子类都需要保存JSON中的所有数据并为其创建实例.
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.
让我们在变量rawData中包含原始JSON字符串:
Let's have the raw JSON string in the variable rawData:
rawData = """{"action":"create","data":{"geometry": {"type": "Point","coordinates": [... """
现在我必须这样做:
>>> 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"
推荐答案
您可以为此创建自己的类.使用__getitem__
和__setitem__
使用点表示法从对象的__dict__
获取和更新值:
You could create your own class for that. Use __getitem__
, and __setitem__
to get and update values from the object's __dict__
using dot notation:
import json
class PyJSON(object):
def __init__(self, d):
if type(d) is str:
d = json.loads(d)
self.convert_json(d)
def convert_json(self, d):
self.__dict__ = {}
for key, value in d.items():
if type(value) is dict:
value = PyJSON(value)
self.__dict__[key] = value
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
rawData = """... raw data ..."""
quake = PyJSON(rawData)
按预期工作:
>>> quake.data.properties.flynn_region
'OAXACA, MEXICO'
编辑:添加了to_dict
并覆盖了__repr__
,因此可以更轻松地在控制台中查看值.将convert_json
重命名为from_dict
.
EDIT: Added to_dict
and overridden __repr__
so it's easier to peek at values in console. Renamed convert_json
to from_dict
.
import json
class PyJSON(object):
def __init__(self, d):
if type(d) is str:
d = json.loads(d)
self.from_dict(d)
def from_dict(self, d):
self.__dict__ = {}
for key, value in d.items():
if type(value) is dict:
value = PyJSON(value)
self.__dict__[key] = value
def to_dict(self):
d = {}
for key, value in self.__dict__.items():
if type(value) is PyJSON:
value = value.to_dict()
d[key] = value
return d
def __repr__(self):
return str(self.to_dict())
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
rawData = """... raw data ..."""
quake = PyJSON(rawData)
之前:
>>> quake.data.geometry
<__main__.PyJSON object at 0xADDRESS>
之后:
>>> quake.data.geometry
{'coordinates': [-95.12, 16.52, -52.0], 'type': 'Point'}
这篇关于从Json字符串创建Python对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!