Decoding JSON

  1. import json
  2. struct Foo {
  3. x int
  4. }
  5. struct User {
  6. name string
  7. age int
  8. // Use the `skip` attribute to skip certain fields
  9. foo Foo [skip]
  10. // If the field name is different in JSON, it can be specified
  11. last_name string [json: lastName]
  12. }
  13. data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25 }'
  14. user := json.decode(User, data) or {
  15. eprintln('Failed to decode json')
  16. return
  17. }
  18. println(user.name)
  19. println(user.last_name)
  20. println(user.age)
  21. // You can also decode JSON arrays:
  22. sfoos := '[{"x":123},{"x":456}]'
  23. foos := json.decode([]Foo, sfoos) ?
  24. println(foos[0].x)
  25. 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.