Skip to content

Commit

Permalink
docs: document [json: ETitle] in vlib/json/README.md too
Browse files Browse the repository at this point in the history
  • Loading branch information
spytheman committed Oct 31, 2023
1 parent e465f74 commit d350a68
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions vlib/json/README.md
@@ -1,9 +1,14 @@
## Description:

`json` provides encoding/decoding of V data structures to/from JSON.

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](https://github.com/vlang/v/blob/master/doc/docs.md#json)
## 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.

```v
import json
Expand All @@ -14,23 +19,28 @@ enum JobTitle {
}
struct Employee {
mut:
name string
family string [json: '-'] // this field will be skipped
age int
salary f32
title JobTitle
title JobTitle [json: 'ETitle'] // the key for this field will be 'MyTitle', not 'title'
}
fn main() {
x := Employee{'Peter', 28, 95000.5, .worker}
x := Employee{'Peter', 'Begins', 28, 95000.5, .worker}
println(x)
//
s := json.encode(x)
println('Employee x: ${s}')
assert s == '{"name":"Peter","age":28,"salary":95000.5,"title":"worker"}'
//
y := json.decode(Employee, s)!
//
println(y)
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
}
```

0 comments on commit d350a68

Please sign in to comment.