Skip to content

Elixir implementation of JsonLogic

License

Notifications You must be signed in to change notification settings

box-id/json_logic_elixir

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JsonLogic

JsonLogic implementation in Elixir.

Forked from liuming/json_logic_elixir and modified by Box ID to allow for project-specific extensions (custom operations) at compile-time.

Installation

This package can be installed by adding json_logic to your list of dependencies in mix.exs:

def deps do
  [
    {:json_logic, github: "box-id/json_logic_elixir"}
  ]
end
iex> JsonLogic.apply(%{"log" => "value"})
"value"

Detailed documentation can be found at https://hexdocs.pm/json_logic.

Custom Operators

To add custom operators to JsonLogic, implement them like in the following example:

defmodule MyApp.JsonLogic do
  use JsonLogic.Base,
    operations: %{
      "regex" => :regex_match
    }

  def regex_match([pattern, field], data) do
    string = if is_map(field), do: __MODULE__.apply(field, data), else: field
    regex = compile_regex(pattern)

    Regex.match?(regex, string)
  end

  defp compile_regex(pattern) when is_binary(pattern), do: Regex.compile!(pattern)

  defp compile_regex(%{"pattern" => pattern, "options" => options}),
    do: Regex.compile!(pattern, options)
end

Extensions

Extensions can be used like this:

defmodule MyApp.JsonLogic do
  use JsonLogic.Base,
    extensions: [JsonLogic.Extension.Obj]

Extensions can bring one or multiple operators. Using extensions is compatible with custom operators.

See the JsonLogic.Extension for how to implement an extension.

Included Extensions

The following extensions are available, but not enabled by default:

Operators Extension Module
obj JsonLogic.Extensions.Obj
replace JsonLogic.Extensions.Replace
encode_json, encode_json_obj JsonLogic.Extensions.EncodeJson

About

Elixir implementation of JsonLogic

Resources

License

Stars

Watchers

Forks

Languages

  • Elixir 99.9%
  • Makefile 0.1%