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

  1. import json
  2. struct Foo {
  3. x int
  4. }
  5. struct User {
  6. // Adding a [required] attribute will make decoding fail, if that
  7. // field is not present in the input.
  8. // If a field is not [required], but is missing, it will be assumed
  9. // to have its default value, like 0 for numbers, or '' for strings,
  10. // and decoding will not fail.
  11. name string [required]
  12. age int
  13. // Use the `skip` attribute to skip certain fields
  14. foo Foo [skip]
  15. // If the field name is different in JSON, it can be specified
  16. last_name string [json: lastName]
  17. }
  18. data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25 }'
  19. user := json.decode(User, data) or {
  20. eprintln('Failed to decode json, error: $err')
  21. return
  22. }
  23. println(user.name)
  24. println(user.last_name)
  25. println(user.age)
  26. // You can also decode JSON arrays:
  27. sfoos := '[{"x":123},{"x":456}]'
  28. foos := json.decode([]Foo, sfoos)?
  29. println(foos[0].x)
  30. println(foos[1].x)

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.

Encoding JSON

  1. import json
  2. struct User {
  3. name string
  4. score i64
  5. }
  6. mut data := map[string]int{}
  7. user := &User{
  8. name: 'Pierre'
  9. score: 1024
  10. }
  11. data['x'] = 42
  12. data['y'] = 360
  13. println(json.encode(data)) // {"x":42,"y":360}
  14. println(json.encode(user)) // {"name":"Pierre","score":1024}