Json.Raw
type Json.Raw = stringJson.Raw is a JSON value kept as its text. Json.decode checks that the text it reads into a Json.Raw is JSON and keeps it as written, for the program to decode at a type once another part of the text has said which. Json.encode and Json.stringify write its tokens as spelled.
Details
Json.decodechecks the kept part as it checks any JSON, and keeps it from its first character to its last, white space and the spelling of numbers and strings included.- A
Json.Rawreads every kind of JSON value,nullincluded, so it shares a union with no other member. A part that may be left out takes a default instead:data: Json.Raw = Json.Raw("null"). Json.encodeandJson.stringifypanic on aJson.Rawwhose text is not one JSON value.
Basic examples
type Event = { type: string, data: Json.Raw }
Json.decode(`{"type": "ping", "data": {"at": 1}}`, type(Event)) // Ok{ value: Event{ type: "ping", data: Json.Raw("{\"at\": 1}") } }
Json.stringify(Json.Raw(`[ 1, 2 ]`)) // "[1,2]"
string(Json.Raw(`[ 1, 2 ]`)) // "[ 1, 2 ]"Scope
The kept text is the value as written, so a number keeps its spelling and its digits, and a string its escapes:
Json.decode(`[9007199254740993, 1.50, "a\u0062"]`, type(Array[Json.Raw])) // Ok{ value: [Json.Raw("9007199254740993"), Json.Raw("1.50"), Json.Raw("\"a\\u0062\"")] }A Json.Raw reads any slot: the whole text, without the white space around it, an element, a map value, or a field. Every kind of value fits, null included:
Json.decode(` {"a": 1} `, type(Json.Raw)) // Ok{ value: Json.Raw("{\"a\": 1}") }
Json.decode(`{"a": {"x": 1}, "b": null}`, type(Map[string, Json.Raw])) // Ok{ value: Map{ "a": Json.Raw("{\"x\": 1}"), "b": Json.Raw("null") } }A kept part is still read as JSON, so malformed text or a repeated name inside it is an Err:
type Event = { type: string, data: Json.Raw }
Json.decode(`{"type": "ping", "data": [1,]}`, type(Event)) // Err{ error: Error{ message: "expected a value, found ']' at line 1, column 29", kind: null } }
Json.decode(`{"type": "ping", "data": {"a": 1, "a": 2}}`, type(Event)) // Err{ error: Error{ message: "duplicate name \"a\" at line 1, column 35", kind: null } }A writer keeps each token as spelled and drops only the white space between them:
Json.stringify(Json.Raw(`[1.50, 1E+2, "a\/b"]`)) // "[1.50,1E+2,\"a\\/b\"]"With indent, the writer follows its own indent, whatever white space the text had:
println(Json.stringify(Json.Raw(`{"a": [1, 2], "b": {}}`), indent: " ")){
"a": [
1,
2
],
"b": {}
}Applications
Read events whose data has a type that depends on type, and decode each part at its own type:
type Event = { type: string, data: Json.Raw }
type Counter = { value: int }
type Ratio = { value: float64 }
func show(body: string): Result[void, Error] {
for event in try Json.decode(body, type(Array[Event])) {
let text = string(event.data)
if event.type == "counter" {
println(try Json.decode(text, type(Counter)))
} else if event.type == "ratio" {
println(try Json.decode(text, type(Ratio)))
}
}
Result.ok(void)
}
show(`[{"type": "counter", "data": {"value": 9007199254740993}}, {"type": "ratio", "data": {"value": 0.5}}]`).unwrap()Counter{ value: 9007199254740993 }
Ratio{ value: 0.5 }An Err from the second decode has a path that starts again at $. Add the outer context with Result.wrapErr:
type Counter = { value: int }
let data = Json.Raw(`{"value": 0.5}`)
Json.decode(string(data), type(Counter)) | Result.wrapErr("$[0].data") // Err{ error: Error{ message: "$[0].data: $.value: want int, got 0.5 at line 1, column 11", kind: null } }Pass a part through unchanged, without decoding it:
type Envelope = { id: int, payload: Json.Raw }
let incoming = Json.decode(`{"id": 7, "payload": {"deep": [true]}}`, type(Envelope)).unwrap()
Json.encode(type(Envelope), Envelope{ ...incoming, id: 8 }) // "{\"id\":8,\"payload\":{\"deep\":[true]}}"Properties and relations
Two Json.Raw values are == when their texts are, so one value written with other white space is not equal. Writing either gives the same text:
let spaced = Json.Raw(`{ "a" : [ 1 ] }`)
let compact = Json.Raw(`{"a":[1]}`)
assert(spaced != compact)
assert(Json.stringify(spaced) == string(compact))A record written with Json.encode reads back with the white space the writer gave its Json.Raw field:
type Event = { type: string, data: Json.Raw }
let event = Event{ type: "ping", data: Json.Raw(`{ "at": 1 }`) }
let t = type(Event)
let back = Json.decode(Json.encode(t, event), t).unwrap()
assert(back.data == Json.Raw(`{"at":1}`))
assert(back != event)Possible issues
Json.Raw | null has no JSON form, since a kept null and the member null are the same text:
type Event = { data: Json.Raw | null }
Json.decode(`{"data": null}`, type(Event)) // panic: Json.decode: Event.data: Json.Raw reads every kind of JSON value, null includedGive the field a default instead, so the object may leave it out:
type Event = { type: string, data: Json.Raw = Json.Raw("null") }
Json.decode(`{"type": "ping"}`, type(Event)) // Ok{ value: Event{ type: "ping", data: Json.Raw("null") } }
Json.decode(`{"type": "ping", "data": null}`, type(Event)) // Ok{ value: Event{ type: "ping", data: Json.Raw("null") } }A Json.Raw you build is checked only when it is written, and text that is not one JSON value panics there. A JSON string in a Json.Raw includes its quotes:
Json.stringify(Json.Raw("[1,")) // panic: Json.stringify: Json.Raw is not JSON: unexpected end of JSON input
Json.stringify(Json.Raw("hello")) // panic: Json.stringify: Json.Raw is not JSON: expected a value, found 'h' at line 1, column 1
Json.stringify(Json.Raw(`"hello"`)) // "\"hello\""A Json.Raw uses its own namespace, not String's, so a string function needs string(raw) first:
let raw = Json.Raw("[1, 2]")
println(raw.length()) // error: Json.Raw has no field or function length
println(string(raw).length())