Values and conversion

The documents of Rego are values: the input, the data and each result. In rego4k, a document is a Value of rego4k.values.

The engine does not read JSON or Kotlin data. Convert them to values at the edge of the application.

The kinds of values

Kind Rego Kotlin data (toKotlin)
Null null null
Bool true, false Boolean
Num 1, 2.5, 1e3 BigDecimal
Str "text" String
Arr [1, 2] List
Obj {"a": 1} Map, in the order of the keys
SetV {1, 2} Set

The values are immutable, and they have the total order of OPA: null < boolean < number < string < array < object < set.

Comparison, hash codes and conversion use loops, not recursion, so a value can have any depth.

From Kotlin data

Value.of converts maps, lists and other iterables, sets, strings, numbers, booleans and null.

toKotlin converts a value back:

Conversions.kt
val input = Value.of(
    "method" to "GET",
    "user" to Value.of("name" to "alice", "roles" to setOf("viewer"), "age" to 42),
    "path" to listOf("reports", 7),
)
// {method=GET, path=[reports, 7], user={age=42, name=alice, roles=[viewer]}}
val kotlin = input.toKotlin()
Conversions.kt, lines 13 to 19, on GitHub

From JSON

JsonReader and JsonWriter of core read and write JSON text, with the results of Go's encoding/json in OPA. A number stays exact, and an error has the message of Go, for example unexpected end of JSON input.

The builtins use this reader, so their results do not change with the JSON library of the application.

rego4k-http4k-json converts the nodes of an http4k Json, for example Moshi, Kondor or Gson. Thus the application keeps its JSON library.

Conversions.kt
// rego4k-core
val withCore = JsonReader.parse(requestBody)
// rego4k-http4k-json, with any http4k Json
val withMoshi = Moshi.parseValue(requestBody)
// a MoshiNode of Moshi
val node = Moshi.fromValue(withMoshi)
// the JSON text, as OPA writes it
val text = JsonWriter.write(withCore).toString()
Conversions.kt, lines 27 to 34, on GitHub

The text of a value

toString of a value gives its Rego text, for example {"roles": {"admin"}} for an object with a set.

A string with bytes that are not UTF-8 shows each such byte as U+FFFD. The builtins that read the bytes, for example base64.encode, read the bytes of the Str.