【问题标题】:Comparing JSON object to a model/filter in python将 JSON 对象与 python 中的模型/过滤器进行比较
【发布时间】:2021-12-29 15:11:59
【问题描述】:

我有一个包含许多对象的 JSON 文件,如下所示:

数据

{
    "cars": [
        {
            "make": "honda",
            "model": "accord",
            "type": "LX",
            "year": 2010,
            "features": [
                { "doors": 4 },
                { "windows": 4 },
                { "avg_horsepower": 200 },
                { "mpg": 30 },
                { "color": "red" }
            ]
        },
        {
            "make": "toyota"
        }
    ]
}

我想根据另一个模型/架构过滤/查询这些对象,如下所示,支持基本逻辑操作。

型号

{
    "cars": [
        {
            "make": "honda",
            "year": {
                "$>=": 2000,
                "$<": 2020
            },
            "features": [
                {
                    "color": {
                        "$or": [
                            "red",
                            "blue"
                        ]
                    }
                }
            ]
        }
    ]
}

我希望能够做到以下几点:

test.py

import json

def test(data, model):
  do_work_here
  if match:
    return True
  else:
    return False

cars = json.loads(data)
model = json.loads(model)

for car in cars:
  print(test(car, model))

预期输出:

True
False

您将如何使用基本逻辑以类似格式针对另一个对象过滤对象列表?或者是否有预先构建的方法来实现这一点?我知道这对于数据库 / SQL / mongo 来说是相当微不足道的,但是对于这种特殊情况,我不需要数据库。

【问题讨论】:

    标签: python json


    【解决方案1】:

    我想你正在寻找JSONSchema。可以看到keywords like minimum, exclusiveMinimum, etc可以用于验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      相关资源
      最近更新 更多