Decoding JSON
1. import json
3. struct Foo {
4. x int
5. }
7. struct User {
8. name string
9. age int
10. // Use the `skip` attribute to skip certain fields
11. foo Foo [skip]
12. // If the field name is different in JSON, it can be specified
13. last_name string [json: lastName]
14. }
16. data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25 }'
17. user := json.decode(User, data) or {
18. eprintln('Failed to decode json')
19. return
20. }
21. println(user.name)
22. println(user.last_name)
23. println(user.age)
24. // You can also decode JSON arrays:
25. sfoos := '[{"x":123},{"x":456}]'
26. foos := json.decode([]Foo, sfoos) ?
27. println(foos[0].x)
28. 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 first is the type into which the JSON value should be decoded and the second is a string containing the JSON data.
V generates code for JSON encoding and decoding. No runtime reflection is used. This results in much better performance.
