1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: add a JSON section, and subsections for encoding and decoding (#13396)

This commit is contained in:
Snavy 2022-02-08 00:18:40 -08:00 committed by GitHub
parent 4ef7d26133
commit f0806822dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -118,7 +118,9 @@ For more details and troubleshooting, please visit the [vab GitHub repository](h
* [Spawning Concurrent Tasks](#spawning-concurrent-tasks) * [Spawning Concurrent Tasks](#spawning-concurrent-tasks)
* [Channels](#channels) * [Channels](#channels)
* [Shared Objects](#shared-objects) * [Shared Objects](#shared-objects)
* [JSON](#json)
* [Decoding JSON](#decoding-json) * [Decoding JSON](#decoding-json)
* [Encoding JSON](#encoding-json)
* [Testing](#testing) * [Testing](#testing)
* [Memory management](#memory-management) * [Memory management](#memory-management)
* [Stack and Heap](#stack-and-heap) * [Stack and Heap](#stack-and-heap)
@ -3714,7 +3716,14 @@ fn main() {
``` ```
Shared variables must be structs, arrays or maps. Shared variables must be structs, arrays or maps.
## Decoding JSON ## JSON
Because of the ubiquitous nature of JSON, support for it is built directly into V.
V generates code for JSON encoding and decoding.
No runtime reflection is used. This results in much better performance.
### Decoding JSON
```v ```v
import json import json
@ -3752,14 +3761,32 @@ println(foos[0].x)
println(foos[1].x) println(foos[1].x)
``` ```
Because of the ubiquitous nature of JSON, support for it is built directly into V.
The `json.decode` function takes two arguments: The `json.decode` function takes two arguments:
the first is the type into which the JSON value should be decoded and the first is the type into which the JSON value should be decoded and
the second is a string containing the JSON data. the second is a string containing the JSON data.
V generates code for JSON encoding and decoding. ### Encoding JSON
No runtime reflection is used. This results in much better performance.
```v
import json
struct User {
name string
score i64
}
mut data := map[string]int{}
user := &User{
name: 'Pierre'
score: 1024
}
data['x'] = 42
data['y'] = 360
println(json.encode(data)) // {"x":42,"y":360}
println(json.encode(user)) // {"name":"Pierre","score":1024}
```
## Testing ## Testing