JSON
Because of the ubiquitous nature of JSON, V provides the pure V json2 module for encoding and
decoding. It uses compile-time reflection instead of runtime reflection.
Decoding JSON
import json2
struct Foo {
x int
}
struct User {
// Adding a [required] attribute will make decoding fail, if that
// field is not present in the input.
// If a field is not [required], but is missing, it will be assumed
// to have its default value, like 0 for numbers, or '' for strings,
// and decoding will not fail.
name string @[required]
age int
// Use the `@[skip]` attribute to skip certain fields.
// You can also use `@[json: '-']`, and `@[sql: '-']`, which will cause only
// the JSON encoder to skip the field, or only the SQL ORM to skip it.
foo Foo @[skip]
// If the field name is different in JSON, it can be specified
last_name string @[json: lastName]
}
data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25, "nullable": null }'
user := json2.decode[User](data) or {
eprintln('Failed to decode json, error: ${err}')
return
}
println(user.name)
println(user.last_name)
println(user.age)
// You can also decode JSON arrays:
sfoos := '[{"x":123},{"x":456}]'
foos := json2.decode[[]Foo](sfoos)!
println(foos[0].x)
println(foos[1].x)
The json2.decode function takes the target type as a generic type argument and the JSON data as
a string argument.
Encoding JSON
import json2
struct User {
name string
score i64
}
mut data := map[string]int{}
user := &User{
name: 'Pierre'
score: 1024
}
data['x'] = 42
data['y'] = 360
println(json2.encode(data, escape_unicode: true)) // {"x":42,"y":360}
println(json2.encode(user, escape_unicode: true)) // {"name":"Pierre","score":1024}
The json2 module also supports anonymous struct fields, which helps with complex JSON APIs with
many levels.
On this page