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.
- A
Numis an exactBigDecimal, so1 == 1.0. It keeps the text of a number from JSON or Rego, for example1.0or1E2, as OPA does. - A
Stris a sequence of bytes, as in Go, and itsvalueis the text. - A key of an
Objcan be any value.
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.
- A
Valuein the data stays as it is. Value.of("method" to "GET")makes an object from its entries, as a map of the entries gives it.- Other data gives an
IllegalArgumentException.
toKotlin converts a value back:
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 GitHubFrom 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.
parseValuereads JSON text.toValueconverts a node.fromValuegives a node. A set becomes an array, and a key that is not a string becomes its JSON text.
// 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 GitHubThe 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.