v/vlib/json
2025-07-02 16:12:03 +03:00
..
cjson docs: put some more dots in the doc comments of public APIs, found by find_doc_comments_with_no_dots.v 2025-07-02 16:12:03 +03:00
tests tools: add support for // vtest vflags: -w in _test.v files, to allow v -W test . later, for files, that have known warnings 2025-06-22 12:43:04 +03:00
json_primitives.c.v json: link with libm (fix #24272) (#24273) 2025-04-21 17:51:46 +03:00
README.md fmt: fix formating a file in an oscillating manner (fix #22223, fix #22026) (#22232) 2024-09-17 09:47:38 +03:00

Description

The json module provides encoding/decoding of V data structures to/from JSON. For more details, see also the JSON section of the V documentation

Examples

Here is an example of encoding and decoding a V struct with several fields. Note that you can specify different names in the json encoding for the fields, and that you can skip fields too, if needed.

import json

enum JobTitle {
	manager
	executive
	worker
}

struct Employee {
mut:
	name   string
	family string @[json: '-'] // this field will be skipped
	age    int
	salary f32
	title  JobTitle @[json: 'ETitle'] // the key for this field will be 'ETitle', not 'title'
	notes  string   @[omitempty]      // the JSON property is not created if the string is equal to '' (an empty string).
	// TODO: document @[raw]
}

fn main() {
	x := Employee{'Peter', 'Begins', 28, 95000.5, .worker, ''}
	println(x)
	s := json.encode(x)
	println('JSON encoding of employee x: ${s}')
	assert s == '{"name":"Peter","age":28,"salary":95000.5,"ETitle":"worker"}'
	mut y := json.decode(Employee, s)!
	assert y != x
	assert y.family == ''
	y.family = 'Begins'
	assert y == x
	println(y)
	ss := json.encode(y)
	println('JSON encoding of employee y: ${ss}')
	assert ss == s
}