将逻辑表示为JSON中的数据 [英] Representing logic as data in JSON

查看:182
本文介绍了将逻辑表示为JSON中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于业务原因,我们需要将一些条件逻辑外部化到外部文件中:最好是JSON。

For business reasons we need to externalize some conditional logic into external files: preferably JSON.

可以通过添加以下节点来处理简单的筛选方案:

A simple filter-by scenario could be handled by adding a node as follows:

"filter": [
  {
    "criteria": "status",
    "value": "open",
    "condition": "=="
  }
]

多个条件可以通过数组。

Multiple conditions could be handled by additional values in the array.

"filter": [
  {
    "criteria": "status",
    "value": "open",
    "condition": "=="
  },
  {
    "criteria": "condition2",
    "value": "value2",
    "condition": "=="
  }
]

但是,当我们处理涉及AND或OR的复杂条件时,这会引起一些困惑。

However, it gets a little confusing when we have handle complex conditions involving ANDs or ORs.

问题:是否存在标准化(甚至被广泛接受) )格式来表示JSON中的此类逻辑?

Question: is there a standardized (or even widely accepted) format for representing such logic within JSONs? How would you do it if it were up to you?

注意:第一个答案已制成可编辑的Wiki,因此任何人都可以改善它。

NOTE: The first answer has been made an editable wiki so it can be improved by anyone who feels it can be.

推荐答案

如果您必须使用标准JSON实现此功能,我建议您使用类似于Lisp的东西 S表达式。条件可以是普通对象,也可以是数组的第一个条目是连接它们的逻辑运算。

If you must implement this using standard JSON, i'd recommend something akin to Lisp's "S-expressions". A condition could be either a plain object, or an array whose first entry is the logical operation that joins them.

例如:

["AND",
    {"var1" : "value1"},
    ["OR",
        { "var2" : "value2" },
        { "var3" : "value3" }
    ]
]

表示 var1 == value1 AND(var2 == value2 OR var3 == value3)

如果您希望简洁而不是一致性,则还可以允许一个对象具有多个属性,这些属性将由AND隐式连接。例如, { a: b, c: d} 等效于 [ AND,{ a: b},{ c: d}] 。但是在某些情况下(如示例),前一种语法不能如实地表示所写的条件。您将需要其他技巧,例如翻译条件或使用虚拟属性名称。后一种语法应始终有效。

If you prefer brevity over consistency, you could also allow an object to have multiple properties, which would implicitly be joined by an AND. For example, { "a": "b", "c": "d" } would be equivalent to ["AND", { "a": "b" }, { "c": "d" }]. But there are cases (like the example) where the former syntax can not faithfully represent the condition as written; you'd need additional trickery like translating the condition or using dummy property names. The latter syntax should always work.

这篇关于将逻辑表示为JSON中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆