Skip to content

7. JSON

Programs often save data as JSON or send it to other programs. #[Core\Json\Derive] is an attribute, a line that adds a feature to the class below it. With it, Novis can write and read the objects of that class as JSON:

<?nvs
// This program turns a list of tasks into JSON text, and reads JSON text back.
#[Core\Json\Derive]
class Task
{
public string $title;
public bool $done;
public function constructor(string $title, bool $done)
{
$this->title = $title;
$this->done = $done;
}
}
array<Task> $tasks = [new Task('Buy milk', true), new Task('Call Ada', false)];
// `Core\Json::encode` gives the JSON text of a value.
echo Core\Json::encode($tasks), "\n";
// `Core\Json::decodeAs` reads JSON text into an object of the class you name.
Task $task = Core\Json::decodeAs<Task>('{"title":"Water the plants","done":false}');
echo $task->title, "\n";
[{&quot;title&quot;:&quot;Buy milk&quot;,&quot;done&quot;:true},{&quot;title&quot;:&quot;Call Ada&quot;,&quot;done&quot;:false}]
Water the plants

Core\Json::encode returns the JSON text of the $tasks array. Each property of a Task becomes a key.

This program prints the JSON with echo. In a web server, echo escapes HTML, so each quote arrives as &quot;. A server sends JSON with Core\Response::sendJson instead. A JSON API shows how.

Core\Json::decodeAs<Task> reads the text into a new Task. It checks each value against the type of its property. If a key is missing or has the wrong type, it throws a ParseError.

Read more in Syntax: JSON.

Next: step 8, tests.