
JsonLogic – Build complex rules, serialize them as JSON - dchuk
http://jsonlogic.com/operations.html
======
jcoffland
Adding computation to a data description language is always a bad idea. I've
seen this done with XML. XSLT is a great example of why this sucks. This has
been done with JSON before anyway. Here are several examples:

[https://github.com/json-schema/json-
schema/wiki/switch-(v5-p...](https://github.com/json-schema/json-
schema/wiki/switch-\(v5-proposal\))
[http://www.ibm.com/support/knowledgecenter/SSEPEK_11.0.0/jso...](http://www.ibm.com/support/knowledgecenter/SSEPEK_11.0.0/json/src/tpc/db2z_jsonlogicaloperators.html)
[https://www.npmjs.com/package/lib-jsl](https://www.npmjs.com/package/lib-jsl)
[http://jsonnet.org/language/design.html](http://jsonnet.org/language/design.html)

~~~
keithb-
Okay, first of all, the current fascination with JSON is not fundamentally
different from the previous fascination with XML. The only thing that anyone
can agree on is that JSON is easy to parse just like its predecessor. This is
why XSLT came into existence: firstly, it was easy to parse, secondly, ...,
thirdly, profit (i.e. reuse, generalization, performance, etc. etc. etc.).

On the other hand, this language is bananas because the programmer is writing
the AST and that is what a parser is supposed to do for him/her. Manually
coding the AST is like harvesting an acre of corn by hand. If you can find a
more inefficient method, then by all means use it.

And just for good measure, XML is not a "data description language", it is a
type system; probably the most complex type system I've ever seen and it
wasn't a bad idea, it was simply more complex than any application would ever
need.

I don't dislike XML, and I think it will continue to live just like Haskell
because every generation will come to understand that its extreme faith in
generalization has little practical use just about the same time that a new
generation first discovers it. So while one is dying to simplify, the other is
dying to espouse the existential core of computer science.

~~~
falcolas
> XML is not a "data description language", it is a type system

XML means "eXtensible Markup Language" \- so pretty much exactly a description
of the data it contains. Granted, you can mark up a bit of data with a type,
but you can mark it up with anything else as well.

I've even seen entire programming languages built upon XML.

~~~
drostie
I actually don't think that would be all bad if you in addition paired some
parsers and serializers for other formats in your standard library.

That could actually be a really fun language: "you can write this in Haskell-
syntax, Python-syntax, or C-syntax, we don't care, just make sure that you
enclose it in the corresponding

    
    
        <parse-as lang="c">
        // ...
        </parse-as>
    

and then `myprogram.c.x` will get compiled to `myprogram.x` which is a
standard XML file, which you can then edit with `x-to-py myprogram.x
>myprogram.py.x && vim myprogram.py.x` and have a field day of it."

Sort of like the PL equivalent of Lennon's _Imagine_.

~~~
falcolas
It was moderately more complicated that this, as it represented the actual
program tree structure within XML. Imagine lisp with XML tags in place of
parentheses.

------
userbinator
For some reason this reminds me of [http://thedailywtf.com/articles/the-inner-
json-effect](http://thedailywtf.com/articles/the-inner-json-effect)

------
dabernathy89
I see a lot of folks who are a lot smarter than me crapping on this, but I
think it could be really useful. I've thought about the problem before of how
to share complex rules between front-end and back-end safely, and came up with
a UI for it:

[https://dabernathy89.github.io/vue-query-
builder/](https://dabernathy89.github.io/vue-query-builder/)

I honestly didn't put too much thought into the actual structure of the JSON,
so I wonder if there is someway I can now integrate JsonLogic into the query
builder.

Good work!

~~~
couchand
I would suggest that, at first glance, your structure is actually preferable
for most applications where this would be useful. The real advantage of a DSL
is when it provides a concise way to solve a specific problem domain. The OP
just provides a verbose way to describe a general problem domain, without any
benefit of regularization.

Your schema, on the other hand, uses explicit node names and types, which
should make automated analysis much simpler and less error-prone. The few
changes I'd suggest are mostly just cosmetic: standardizing the schema (the
type radio seems to imply the operator equals), renaming properties (why
selectedOperator when just operator will do?), and maybe compressing levels
where appropriate, for instance the query-builder-group could itself have the
logicalOperator property.

~~~
dabernathy89
that makes sense - and thanks for the feedback!

------
banachtarski
So, a JSON AST. The whole point of programming languages is to give you
something better than an AST to work with. Code is already data and we have
functions for evaluating/compiling/interpreting said data natively/in-vms/in-
interpreters.

------
SloughFeg
Reminds me of the early 00s where everyone and their son were making
unmaintainable DSLs in XML

~~~
virtualized
People still make them. Because, you know, "everyone can use them" and they
are "simple". In reality, only software developers are able to do anything
with such a crap DSL and it takes a lot more effort and workarounds to get
anything done vs a sane programming language.

~~~
mvitorino
Even if only the developers can use a DSL, that doesn't not mean DSLs don't
have a place as a solution and that a generic programming language is always
preferable.

In complex enough domains DSLs can be key to tackle that complexity and they
can take many forms.

------
al2o3cr
Two thoughts on this:

(1) We have a similar sort of "expression language" at my job; in our case,
the value it provides is ready access to the pseudo-AST we parse it into. We
transform that AST at runtime (along with subexpression results) into a human-
friendly error message like "Total Amount must be less than $X when Blah
Mumble is under Y". The downside is that that "configuration" data now behaves
more like code but doesn't have any of the tooling of the host language: we've
had to add specific code to provide a stacktrace-equivalent hint about where
expression evaluation failed.

(2) The bummer design decision in JsonLogic, IMO, is the leakage of the JS
equality operator into what _could_ have been a language-agnostic description.
That's going to be nasty to implement elsewhere.

------
ctvo
There are use cases for rule-based logic like this stored outside of
application code and JSON is a very easy format regardless of warts.

The amount of salt in here from 1) Gross JSON! 2) why did you implement an
AST?! is astounding.

------
emilong
Is there a security statement about this? I don't immediately see any
dangerous operations, but code sharing should always be suspect. If this
catches on, it won't be long before someone asks for something that would open
vulnerabilities.

All that being said, this is a really interesting approach and having a
language for shared, declarative logic is often useful.

~~~
pkghost
If you're building an extensible platform of some kind, maybe, but otherwise
I'd use a build system.

------
michaelcampbell
Jelly, anyone?
[https://en.wikipedia.org/wiki/Apache_Jelly](https://en.wikipedia.org/wiki/Apache_Jelly)

~~~
fbreduc
Lisp anyone?

------
fiatpandas
Looking over the examples, I thought of MongoDB's aggregation pipeline. You
pass in a similar tree of JSON-only logic to perform more complex database
operations/transformations. In Mongo's case, the idea is to have direct access
to "native" calls, skipping Javascript execution altogether.

------
shanemhansen
These mini-languages almost always become really painful to work with. If I
find myself needing to implement some sort of configurable shared thing more
complex than a table of regular expressions I just jump straight to the
endgame and embed lua or a lisp.

I think the target audience of JsonLogic is sharing code on the
frontend/backend. I think these days javascript is common for that. A tiny
lisp would be suitable as well.

There's a special place in hell reserved for people who make me edit ad-hoc
turing complete configuration languages embedded in json or xml.

------
ilaksh
I believe that eventually software development may move in general to
structured serializations rather than plain text. The main thing holding that
back is just that programming is defined by cryptic colored text and they are
afraid they won't look technical enough if they don't stick to that. I am a
programmer myself btw and of course I use text editors.

~~~
Zecc
Source code _is_ a structured serialization. And it also happens to be plain
text.

Edit: or were you referring to data rather than logic?

~~~
murukesh_s
If data can be code, code can be data too. There are people who hated react
for mixing view with logic.

~~~
TeMPOraL
Possibly another example of the common mistake of web developers - extending
"don't put _business_ logic in views" to "don't put _logic_ in views". That
leads to invention of the silly things called "template languages", which
desperately try (and fail) to avoid being programming languages, and they
create a mess because they manually glue HTML (which is a _tree_ ) from dumb
strings.

------
eschutte2
Pretty cool. Coincidentally I just spent the last couple days implementing
configurable JSON-serialized rules in our app. The bigger part of the
challenge for us was coming up with a human-friendly UI for defining the
rules.

~~~
thom_nic
Been considering the same problem here - how to allow some sort of user-
defined rules/ logic flow? The UI is indeed more difficult to (well) do than
the data representation of said rules. Anything you can share?

~~~
existencebox
It's funny this discussion comes up now, since I've been working on this exact
same problem for an odd week on and off now. Building the syntax, interpreter,
serializer/deserializer took a day. Writing the JS to render it? Still working
on it. (largely hindered by my being a backend eng masquerading as a terribly
incompetent frontend web dev)

My approach however was to treat it as a literal syntax tree. we can represent
trees reasonably well graphically, and if you connect the blocks sensibly you
can make the visualization even flow well enough. Things start to decay past
certain levels of depth; and I've addressed that with modularity. A tree can
be "named" and become a single node within another tree. (yes yes rewriting
programming languages badly or something).

Thus far the biggest problems I've had with this approach have been primarily
just learning the words I need to use to search for the right concepts in web-
UX space; I've actually been pretty damn happy with the view.

Tech wise, just a grid, jquery, bootstrap.

------
asciimike
When you're building a serverless framework with the goal of direct client
access to managed infrastructure without writing server side code, rules
languages like this are an awesome tool to have. You need to: authenticate
users, authorize their actions, validate schema, ensure referential integrity,
and perform business logic checks.

Most (if not all) BaaS platforms have something like this:

\- Firebase: Database Rules
([https://firebase.google.com/docs/database/security/](https://firebase.google.com/docs/database/security/)),
Storage Rules
([https://firebase.google.com/docs/storage/security/](https://firebase.google.com/docs/storage/security/))

\- Parse: Roles and ACLs
([https://parseplatform.github.io//docs/js/guide/#roles](https://parseplatform.github.io//docs/js/guide/#roles))

\- Horizon:
[http://horizon.io/docs/permissions/](http://horizon.io/docs/permissions/)

\- Couchbase Mobile:
[http://developer.couchbase.com/documentation/mobile/1.3/deve...](http://developer.couchbase.com/documentation/mobile/1.3/develop/guides/sync-
gateway/authorizing-users/index.html)

\- Deepstream: [https://deepstream.io/docs/server/valve-
permissions/](https://deepstream.io/docs/server/valve-permissions/)

When used for AuthN/Z, most seem to align with Role Based Access Control
(RBAC), while others go for Attribute Based Access Control (ABAC). The former
is generally easier to reason about and build, while the latter is more
powerful though harder to build and explain.

Most IaaS IAM systems (like those in AWS
[[http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_po...](http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html)],
GCP
[[https://cloud.google.com/compute/docs/access/iam]](https://cloud.google.com/compute/docs/access/iam\]))
are RBAC, while BaaS solutions seem to trend to ABAC for schema validation +
business logic.

Kubernetes also has a cool way of doing this:
[http://kubernetes.io/docs/admin/authorization/](http://kubernetes.io/docs/admin/authorization/)

Disclosure: I work on this at Firebase

~~~
sandGorgon
is something like this applicable for complex math formula as well. For
example if you were building a web based financial spreadsheet.

------
iamleppert
Please not another DSL. We already have a way to express logic; it's called
code.

If you want to make a different programming language that's fine. Data is
code.

Maybe what you really want is a finite state machine? [http://machina-
js.org/](http://machina-js.org/)

~~~
GuiA
I recently implemented a DSL for an environment that I wrote for a fairly
niche purpose, accompanied with a graphical application to build "programs" in
that DSL, because my users are non programmers that need to express domain
specific logic.

It has saved us hundreds if not thousands of man hours on something mission
critical to the company, all while empowering the end users, giving my
programmers more latitude to operate, and separating nicely the generic
environment from the specifics that are irrelevant to it.

There are many ways to solve a problem, and the right one is highly context
dependent. Dismissing something just on the basis of "we already have a way to
express logic; it's called code" seems very narrow minded and not like the
best way to produce solid engineering work.

I can also highly recommend Fowler's "Domain Specific Languages" book, which
gives me the backing to say that I am far from alone in having success with
that approach.

[http://martinfowler.com/bliki/DomainSpecificLanguage.html](http://martinfowler.com/bliki/DomainSpecificLanguage.html)

~~~
hvidgaard
A DSL is fine, encouraged even, for solving specific problems. JsonLogic
however seems like a general tool looking for a job, but I maybe I just
haven't seen its usecase yet.

It looks as a way to move business rules entirely to the backend, but still
have the frontend executing them. I can see the value in that if you
desperately need to reduce the load on your backend.

~~~
softawre
Javascript is the way we execute the same rules on the front/back.

~~~
pmontra
Or any language that runs in the backend and compiles to JS for the frontend.
Rxample: if you have a Rails backend you might consider to use Opal for the
code shared between the server and the browser. This JSON logic would be
there.

------
itaifrenkel
ElasticSearch new Painless scripting language is a secure lava-like DSL
language which is a superset to just logic. Although it seems to be jvm
opinionated.

[https://www.elastic.co/guide/en/elasticsearch/reference/mast...](https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-
scripting-painless.html)

------
donpdonp
Ambitious developer discovers abstract syntax trees expressed as JSON, film at
11.

~~~
bbcbasic
But what if the code was just the same as the data. The code could process
other code as if it were just data.

What would THAT language be like?

~~~
jcoffland
It's called Lisp.

~~~
ENGNR
Lisp -> Scheme -> Javascript -> JSON -> Lisp

Yep, it's come full circle!

~~~
spleeder
[https://github.com/kanaka/miniMAL](https://github.com/kanaka/miniMAL)

------
ckarthik17
We built a system, where user can construct complex search criteria and
submitted for result. We were passing the criteria using a custom dsl (lot of
coding in front-end to construct and parsing logic in back-end).

This will be a perfect match for those kind of cases.

------
chukye
I don't understand... Why just dont get all the complex logic from
server/client, generate a .js with it and use in server/send to client? Why
JSON? JSON is not designed for this.

------
mshenfield
One use case might be the backend of a logic engine a la Drools. I imagine
that needs a well defined, serializable subset of a full programming language.

------
rubyfan
I've seen similar XML based approaches for expressing configurable business
rules but never any as JSON. Love it

------
softwarelimits
[https://en.wikipedia.org/wiki/Business_Process_Modeling_Lang...](https://en.wikipedia.org/wiki/Business_Process_Modeling_Language)

[http://bpmn.io/](http://bpmn.io/)

------
alanh
Here to say JSON is not a good place to encode logic because JSON doesn’t
allow comments, and whenever you are encoding logic, you are going to have to
clarify that $conterintuitive_rule is needed because $stakeholder decided
$such_and_such.

OK, I’m done shitting all over what’s probably a perfectly cromulent library
now…

------
liquidise
As a strictly experimental project, i applaud this effort and i hope the
author learned a lot about building a library. The web presentation is above
average as far as library projects go.

As the library itself, i would't touch this with a 100 foot pole. Serializing
logic shatters encapsulation as well as cohesion, both cornerstone object
oriented principles. Also, when you serialize logic, you leave yourself
handicapped to fix code bugs, as your code bugs are now data bugs by
definition. Imagine solving an off-by-one style error in persisted JSON logic.
Your choices would be regex (shiver) or a script to parse all json blocks and
modify accordingly? Yikes.

As an experiment, this is quite nice. Perhaps too nice. Given the quality of
presentation, i feel bad for the shops that decide to adopt this into
production usage.

~~~
btown
As soon as you begin accepting user data, all your code bugs, even those as
simple as forgetting to collect some metadata you might need later, are data
bugs. And to the specific point about serializing logic being considered
harmful, I'm sure
[https://www.periscopedata.com/](https://www.periscopedata.com/) would beg to
differ!

Seriously, though, there's nothing wrong with using this for a presentation
layer. Define a group of user-selectable client-side filters in a JSON
constants document, which will have a much smaller "error surface" than
defining custom filter functions. Just because it looks like JSON doesn't mean
it necessarily needs to be serialized.

That said, there are a number of inefficiencies in the implementation.
Certainly not production ready, but a great effort.

------
bboreham
As others have said, this is code.

In my experience, folks writing code come to need a VCS ("oops, didn't mean to
change that"), a debugger ("why did it do that?"), a test environment ("what
happens if I change that"), and perhaps an audit trail ("who changed that?").

Set against that, the effort required to parse expressions is trivial.

~~~
zamalek
> Set against that, the effort required to parse expressions is trivial.

Especially s-expressions.

------
sandGorgon
has anyone built a system where complex math had to be made part of the
system... yet had to be user editable?

would something like this help?

------
yogthos
Greenspun's tenth rule in action.

~~~
efaref
Greenspun's tenth rule meets Atwood's law?

------
sriram_iyengar
interesting - but why would i use jsonlogic instead of javascript ?

~~~
thom_nic
Allowing user-defined rules comes to mind. AFAIK `eval()`-ing user input is
can't be done in a safe way. Probably OK on browser but not on the server.

~~~
flushot
I don't see why a language like JS couldn't be used for evaluating rules when
sandboxed. Looks like there's a project that does just that:
[https://developers.google.com/caja/](https://developers.google.com/caja/)

------
bschwindHN
The only thing that comes to mind is a poor man's Clojure(Script)

------
tk120404
why suddenly everybody is talking abt this when nobody noticed it when it was
post 2 months back?

------
zn44
Made me think of [http://thedailywtf.com/articles/the-inner-json-
effect](http://thedailywtf.com/articles/the-inner-json-effect)

------
bbcbasic
Reminds me of
[https://www.elastic.co/guide/en/elasticsearch/reference/curr...](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-
dsl-and-query.html)

