【发布时间】:2016-09-01 15:49:35
【问题描述】:
我正在使用 Python (v3.5) 抓取一个复杂的 MongoDB 文档,我应该更新其中的一些值,这些值分散在对象周围并且在结构中没有特定模式并将其保存回不同的 MongoDB收藏。对象如下所示:
# after json.loads(mongo_db_document) my dict looks like this
notification = {
'_id': '570f934f45213b0d14b1256f',
'key': 'receipt',
'label': 'Delivery Receipt',
'version': '0.0.1',
'active': True,
'children': [
{
'key': 'started',
'label': 'Started',
'children': [
'date',
'time',
'offset'
]
},
{
'key': 'stop',
'label': 'Ended',
'children': [
'date',
'time',
'offset'
]
},
{
'label': '1. Particulars',
'template': 'formGroup',
'children': [
{
'children': [
{
'key': 'name',
'label': '2.1 Name',
'value': '********** THIS SHOULD BE UPDATED **********',
'readonly': 'true'
},
{
'key': 'ims_id',
'label': '2.2 IMS Number',
'value': '********** THIS SHOULD BE UPDATED **********',
'readonly': 'true'
}
]
},
{
'children': [
{
'key': 'type',
'readonly': '********** THIS SHOULD BE UPDATED **********',
'label': '2.3 Type',
'options': [
{
'label': 'Passenger',
'value': 'A37'
},
{
'label': 'Cargo',
'value': 'A35'
},
{
'label': 'Other',
'value': '********** THIS SHOULD BE UPDATED **********'
}
]
}
]
}
]
},
{
'template': 'formGroup',
'key': 'waste',
'label': '3. Waste',
'children': [
{
'label': 'Waste',
'children': [
{
'label': 'Plastics',
'key': 'A',
'inputType': 'number',
'inputAttributes': {
'min': 0
},
'value': '********** THIS SHOULD BE UPDATED **********'
},
{
'label': 'B. Oil',
'key': 'B',
'inputType': 'number',
'inputAttributes': {
'min': 0
},
'value': '********** THIS SHOULD BE UPDATED **********'
},
{
'label': 'C. Operational',
'key': 'C',
'inputType': 'number',
'inputAttributes': {
'min': 0
},
'value': '********** THIS SHOULD BE UPDATED **********'
}
]
}
]
},
{
'template': 'formRow',
'children': [
'empty',
'signature'
]
}
],
'filter': {
'timestamp_of_record': [
'date',
'time',
'offset'
]
}
}
我最初的想法是将占位符(如 $var_name)放在我需要更新值的地方,并使用 Python 的 string.Template 加载字符串,但不幸的是,这种方法会破坏同一个 MongoDB 的其他用户的很多东西出于某种原因记录。
有没有一种解决方案可以简单地修改这种对象而无需“硬编码”路径来查找我需要更新的值?
【问题讨论】:
-
您是在问如何动态找到这些值的路径吗?
-
我知道由于某种原因您无法再次加载、修改和另存为 json?
-
@C14L 好吧,是的,你可以这样表述我的问题 :) 我可以编写一个函数来遍历整个 dict 并寻找每一种可能性,但我在想是否有有更简单的解决方案吗?
-
你能提供更多细节吗?也许是一个例子?这种“假设性”的问题是不可能找到答案的。
-
@Roberto 是的,同样的对象用在 JavaScript、PostgreSQL 中,并且在另一端被解析,所以现在放置像
$var_name这样的占位符非常棘手。
标签: python json mongodb python-3.x