Decode JSON in V

Posted by yhuang
Last Edited by dhonx
Public (Editable by Users)
V
None
Edit
// JSON is very popular nowadays, that's why JSON support is built in.
// The first argument of the json.decode function is the type to decode to. 
// The second argument is the JSON string.
// V generates code for JSON encoding and decoding. No runtime reflection is used.
// This results in much better performance.

import json

struct Foo {
	bar int
}

struct User {
	name string
	age  int

	// Use the `skip` attribute to skip certain fields
	foo Foo [skip]  

	// If the field name is different in JSON, it can be specified
	last_name string [json:lastName]  
}

data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25 }'
user := json.decode(User, data) or {
	eprintln('Failed to decode json')
	return
}
println(user.name)
println(user.last_name)
println(user.age)