jsonLogic

eunyeong·2023년 4월 19일
0

jsonlogic.com

왜 jsonLogic을 사용하는가?

jsonLogic은 완전한 프로그래밍 언어는 아니지만 한가지 결정을 위임하기에 작고, 안전한 방법중 하나이다. 규칙과 데이터를 이용하여 사용자 액션으로부터 동적으로 만들어 질 수 있다.

jsonLogic의 형태

{"operator" : ["values" .. ] }
언제나 이 형태를 가진다.

예시

jsonLogic.apply({"==" : [1, 1] }); ==> true 반환
jsonLogic.apply({"and" : [ { ">" : [3,1] }, { "<" : [1,3] } ] } ); ==> true 반환
jsonLogic.apply({"var": ["a"] }, { a: 1, b: 2} ); ==> 1 반환
jsonLogic.apply(
{"var" : 1 },
[ "apple", "banana", "carrot" ]
); ==> banana 반환 (rule과 data를 바깥에서 정의할 수도 있다)
jsonLogic.apply(true, data_will_be_ignored); ==> 언제나 true 반환
jsonLogic.apply(false, i_wasnt_even_supposed_to_be_here);==> 언제나 false 반환

지원되는 연산자들

Accessing Data

  • var
  • missing
  • missing_some

Logic and Boolean Operations

  • if
  • ==
  • ===
  • !=
  • !==
  • !
  • !!
  • or
  • and

Numeric Operations

  • <, >, >= and <=
  • Between
  • max and min
  • Arithmetic, + - * /
  • %

Array Operations

  • map, reduce, and filter
  • all, none, and some
  • merge
  • in

String Operations

  • in
  • cat
  • substr

Miscellaneous

  • log

함수 정의

var plus = function(a,b){ return a+b; };
jsonLogic.add_operation("plus", plus);

jsonLogic.apply({"plus":[23, 19]}); //Returns 42
jsonLogic.add_operation("Math", Math);
//Note the empty array for no arguments
jsonLogic.apply({"Math.random":[]}); //Returns a float between 0 and 1
jsonLogic.apply({"Math.abs":-42}); //Returns 42
jsonLogic.apply({"Math.ceil":41.001}); //Returns 42
jsonLogic.apply({"Math.log":1739274941520497700}); //Returns 42
jsonLogic({"unless" : [
  {"is_working" : {"var":"user"}},
  {"will_work" : "nothing"}
]}); ==> 가장 안의 괄호부터 차근차근 진행된다 user가 is_working 하지 않으면(unless) nothing will_work라는 의미이다.

파이썬 소스코드

https://github.com/nadirizr/json-logic-py 참조

profile
아무것도 모르는 초보

0개의 댓글