A dynamic value for data whose shape you do not know in advance; the shared language of every format in this group.
import encoding.value
Value is the dynamic data type shared by the encoding packages. One Value is a null, a bool, a 64-bit int, a float, a string, an array of values or an object mapping strings to values, and its kind field says which. encoding.json, encoding.yaml, encoding.toml, encoding.msgpack and others decode into it and encode from it, and encoding.serde converts between formats through it.
Reach for a Value when the shape of the data is not known when you write the program: a webhook payload, a config with optional sections, a document you only pass along. When the shape is fixed, decoding straight into a struct (for example with json.Unmarshal) is shorter and checks the types for you.
The As functions never check the kind.AsString of a number is "" and AsInt of a string is 0. When the data comes from outside, use the checked methods instead: v.field("port").int() throws MissingKey or TypeMismatch with a message that names the key and both kinds, and try v.field("port").int() catch 8080 gives a default.
•
Missing is null, all the way down.ObjectGet on a missing key, or on something that is not an object, returns null, so a chain like ObjectGet(ObjectGet(doc, "a"), "b") is safe. ArrayGet is not: an index past ArrayLen stops the program.
•
Copies share parts. A copy of an object shares its map, so ObjectSet through the copy changes the original. A copy of an array shares its elements but not its length, so ArrayPush on an array you got from ObjectGet is lost until you ObjectSet it back. Use ValueClone for a real copy.
•
Key order depends on how the object was built.ObjectKeys returns keys in the order they were added with ObjectSet, and a decoded JSON document in the order of its text. An object made from a map by ValueObject follows that map's own order. Sort the keys, or encode with sort_keys, when output must be alphabetical.
Guide: walk a whole document
A recursive function over Value handles any shape: for an object, visit each key; for an array, each index; anything else is a leaf. This one prints the path of every leaf, which is handy for logging a webhook payload or comparing two documents line by line.
ObjectKeys gives the keys in the order they were added, so a decoded document keeps the order of its text. This program sorts them with sort.QuickSort to print them alphabetically whatever order the input had. ToDebugString shows each leaf together with its kind.
Guide: build a payload with optional fields
A struct always writes all its fields. When some fields should only appear when they have a value, as many HTTP APIs expect, build a Value object instead and set only what you have. json.Encode with sort_keys prints it in a stable order.
encoding-value-guide-build.salam
import encoding.value
import encoding.json
funcpayload(name: str, email: str, age: int, tags: Vector<str>): value.Value:
mut v := value.NewValueObject()
value.ObjectSet(v, "name", value.ValueString(name))
if email != "":
value.ObjectSet(v, "email", value.ValueString(email))
endif age > 0:
value.ObjectSet(v, "age", value.ValueInt(age))
endif tags.Len() > 0:
mut arr := value.NewValueArray()
each t in tags:
value.ArrayPush(arr, value.ValueString(t))
end
value.ObjectSet(v, "tags", arr)
endret v
endfuncmain:
opts := json.JSONOptions { sort_keys = true }
mut tags := Vector {} asVector<str>
println json.Encode(payload("Sara", "", 0, tags), opts)
tags.Push("beta")
tags.Push("vip")
println json.Encode(payload("Reza", "reza@example.com", 41, tags), opts)
end
To change something deep in a decoded document, take the inner part with ObjectGet, change it, and store it back with ObjectSet. For objects the store is not strictly needed, because the map is shared, but for arrays it is: the program below shows the new order line missing until the array is set back.
Always writing the changed part back with ObjectSet makes the code correct for both kinds, and keeps working if the representation changes. The last line reads a field of a shipping object that does not exist: the chain of ObjectGet calls returns null and AsString gives an empty string, with no crash. The checked form, order.field("shipping"), throws instead and names the missing key, which is what you want when the field is required.
Guide: deep merge of settings
Settings often come in layers: built-in defaults, then a file per site. A deep merge keeps every default the site file does not mention and replaces only what it does, one level at a time. Arrays and plain values in the override win as a whole.
encoding-value-guide-merge.salam
import encoding.value
import encoding.json
funcmerge(base: value.Value, over: value.Value): value.Value:
ifnot value.IsObject(base) ornot value.IsObject(over):
ret value.ValueClone(over)
endmut out := value.ValueClone(base)
each k in value.ObjectKeys(over):
o := value.ObjectGet(over, k)
if value.ObjectHas(out, k):
value.ObjectSet(out, k, merge(value.ObjectGet(out, k), o))
else:
value.ObjectSet(out, k, value.ValueClone(o))
endendret out
endfuncmain throw:
defaults := try json.Decode(
`{"server": {"host": "0.0.0.0", "port": 8080}, "log": {"level": "info", "json": false}, "plugins": ["auth"]}`
)
site := try json.Decode(
`{"server": {"port": 9000}, "log": {"level": "debug"}, "plugins": ["auth", "cache"]}`
)
cfg := merge(defaults, site)
println json.Encode(cfg, json.JSONOptions { indent = " ", sort_keys = true })
println"defaults untouched:", try defaults.field("server").field("port").int()
end
The function clones what it keeps, so defaults is the same afterwards. Without the clones, the result would share its objects with the inputs, as the next section shows.
Guide: copies, conversions and missing keys
Assigning a Value to a new variable does not copy its contents: an object's fields live in a shared map, so a change through the copy shows up in the original. Call ValueClone when you need an independent copy, and ValueFree when you are done with it. Free only values nothing else shares, since freeing a plain copy also frees the original's map.
encoding-value-guide-pitfalls.salam
import encoding.value
funcmain:
mut a := value.NewValueObject()
value.ObjectSet(a, "n", value.ValueInt(1))
mut shared := a
value.ObjectSet(shared, "n", value.ValueInt(2))
println"after editing a plain copy:", value.AsInt(value.ObjectGet(a, "n"))
mut own := value.ValueClone(a)
value.ObjectSet(own, "n", value.ValueInt(3))
println"after editing a clone:", value.AsInt(value.ObjectGet(a, "n"))
println"AsInt of 2.9:", value.AsInt(value.ValueFloat(2.9))
println"AsFloat of 3:", value.AsFloat(value.ValueInt(3))
println"AsInt of \"5\":", value.AsInt(value.ValueString("5"))
println"1 equals 1.0:", value.Equal(value.ValueInt(1), value.ValueFloat(1.0))
mut found := false
_ := value.ObjectGetOk(a, "missing", found)
println"missing key found:", found
value.ValueFree(own)
end
Output
after editing a plain copy: 2
after editing a clone: 2
AsInt of 2.9: 2
AsFloat of 3: 3
AsInt of "5": 0
1 equals 1.0: false
missing key found: false
•
AsInt cuts a float toward zero and AsFloat widens an int, but neither parses text: a string gives 0. Check the kind first with IsInt, IsNumber or IsString.
•
Equal compares kinds too, so the integer 1 and the float 1.0 are different values.
•
ObjectGet on a missing key gives a null value; ObjectGetOk also tells you whether the key was there, and field throws MissingKey for it while an explicit null comes back as a null value.
A dynamic value: null, boolean, whole number, decimal, string, array or object.
Name
Type
Description
kind
int
The kind of the value; one of the Kind constants.
b
bool = false
The boolean value.
i
i64 = 0
The whole number value.
n
f64 = 0
The decimal value.
s
str = ""
The string value.
arr
Vector<Value>
The elements of an array.
obj
HashMap<str, Value>
The keys and values of an object.
order
i64 = 0
An internal handle to the list that records the order in which keys were added to an object with ObjectSet. ObjectDelete keeps it up to date. Do not use it directly; ObjectKeys reads it.
The value of a key in an object. Throws MissingKey when the key is absent and TypeMismatch when the value is not an object, so a missing key and an explicit null are told apart.
Lamp
19.5
12
true
light
missing key -> missing key 'color'
out of range -> index 5 is out of range for an array of 2
type mismatch -> expected an integer, got a string
count or default: 0
The keys of an object. Keys added with ObjectSet come in the order they were added; the keys of an object made from a map by ValueObject come in that map's own order.