【发布时间】:2021-06-09 19:56:23
【问题描述】:
我需要取一个JSON(过滤数据的条件),示例数据:
query = { "and": [
{
"field": "model",
"operator": ">",
"value": "2005"
},
{
"or": [
{
"field": "brand",
"operator": "=",
"value": "Mercedes"
},
{
"field": "brand",
"operator": "=",
"value": "BMW"
}
]
}
]
并编写一个函数,将此 JSON 转换为 MongoDB 查询,以便在从 MongoDb 读取时直接过滤数据(我将在 apache beam ReadFromMongoDB 函数中使用此数据,作为过滤器对象)
所以输出应该是这样的:
{'$and': [{'field': 'model', 'operator': '>', 'value': '2005'}, {
'$or': [
{'field': 'brand', 'operator': '=', 'value': 'Mercedes'},
{'field': 'brand', 'operator': '=', 'value': 'BMW'}
]
}]}
(我有一个函数可以将每个对象转换为 MongoDB 查询,所以不用担心)
我尝试了什么
由于我不知道嵌套数据是如何产生的,所以我在函数中使用了递归。但它变得复杂,输出不符合我的预期。
def splitToItems(query, items={}):
if 'and' in query:
for item in query['and']:
if 'and' in item or 'or' in item:
splitToItems(item)
else:
if '$and' not in items:
items['$and'] = [item]
# print(items)
else:
items['$and'].append(item)
# print(items)
if 'or' in query:
for item in query['or']:
if 'and' in item or 'or' in item:
return splitToItems(item)
else:
if '$or' not in items:
items['$or'] = [item]
# print(items)
else:
items['$or'].append(item)
# print(items)
print(items)
-------
OUTPUT:
# '$or' should have been inside of the first array in this case
{
'$and': [{'field': 'model', 'operator': '>', 'value': '2005'}],
'$or': [{'field': 'brand', 'operator': '=', 'value': 'Mercedes'}, {'field': 'brand', 'operator': '=', 'value': 'BMW'}]
}
关于如何改进此功能或使其工作的任何想法?非常感谢提前
【问题讨论】:
标签: python json python-3.x django mongodb