Skip to content

Core\Json::encode

Core\Json::encode(
    mixed $value,
    {pretty?: bool, escapeUnicode?: bool},
): string

Writes a value as JSON text and returns it as a string.

A list becomes a JSON array. An array with string keys or a shape becomes a JSON object. An instance of a class with #[Core\Json\Derive] becomes an object with one key for each public property.

A time value or a Core\Uuid becomes a JSON string. A date or a time is its ISO text, such as "2026-05-14". A Duration is text such as "1h30m", and a Zone is its name. Core\Json::decodeAs reads each one back.

The text is on one line, and pretty: true puts each value on its own line. escapeUnicode: true writes each character outside ASCII as a \u code. The characters <, >, & and ' are always \u codes, so the text is safe inside an HTML page.

encode throws a LogicError for a float that is NaN or infinite, or an object that contains itself.

The examples below write a list, readable JSON, an API response from a class, and time values.

Parameters

  • $valuemixedThe value to encode: null, bool, int, uint, float, decimal, string, an array, a { name: value } shape, or an instance of a class with #[Json\Derive]. A Core\Time\Date, TimeOfDay, DateTime, Instant, Duration, Zone or Core\Uuid is written as a JSON string. A date or a time is its ISO text, a Zone is its name, such as "Europe/Vienna", and a Duration is text such as "1h30m".

Options

  • prettybooloptionalWrites the output across several lines, with indentation. By default, the output is on one line.
  • escapeUnicodebooloptionalWrites every non-ASCII character as a \uXXXX escape. By default, UTF-8 text is written as it is.

Return value

Returns string. The JSON text. It is a tainted string when $value can contain text from outside the program. Tainted text is text that you must check before you use it. A tainted string, or a mixed or object value, anywhere inside $value makes the result tainted.

Errors

  • LogicError$value contains something that JSON cannot represent. This is a NaN or infinite float, a value of a type with no JSON form, an instance of a class without #[Json\Derive], or more than 1024 levels of nesting.

Changelog

VersionChange
0.0.6A Core\Time\Date, TimeOfDay, DateTime, Duration, Zone or Core\Uuid is now a JSON string, as Instant already was. A time zone is written as its name, such as "Europe/Vienna". A text that is not valid throws a ParseError that names its key.

Examples

Basics

<?nvs
// Shows how to write a list and an array with string keys as JSON text.
// A list becomes a JSON array. This prints `[1,2,3]`.
echo Core\Json::encode([1, 2, 3]), "\n";
// An array with string keys becomes a JSON object. This prints `{"name":"Ada","age":36}`.
echo Core\Json::encode(['name' => 'Ada', 'age' => 36]), "\n";
Output
[1,2,3]
{"name":"Ada","age":36}

Pretty

<?nvs
// Shows how to write JSON that is easy for a person to read.
// `pretty: true` puts each value on its own line and indents it by two spaces.
echo Core\Json::encode(['tags' => ['fast', 'safe']], { pretty: true }), "\n";
Output
{
"tags": [
"fast",
"safe"
]
}

Answering an api request

<?nvs
// Shows a program that builds the JSON answer of an API request from its own classes.
// `#[Core\Json\Derive]` gives the class a JSON format. Each public property is one key.
// `#[Core\Json\Field]` sets a different key name for one property.
#[Core\Json\Derive]
class Product
{
public string $name;
#[Core\Json\Field(name: 'price_cents')]
public int $cents;
public function constructor(string $name, int $cents)
{
$this->name = $name;
$this->cents = $cents;
}
}
array<Product> $products = [new Product('Tea', 450), new Product('Café au lait', 380)];
// An array of instances becomes a JSON array of objects.
// This prints the list on one line, with "é" as it is.
echo Core\Json::encode({ page: 1, products: $products }), "\n";
// `escapeUnicode: true` writes each character outside ASCII as a `\u` code.
// This prints the same list with "é" written as `é`.
echo Core\Json::encode({ page: 1, products: $products }, { escapeUnicode: true }), "\n";
Output
{"page":1,"products":[{"name":"Tea","price_cents":450},{"name":"Café au lait","price_cents":380}]}
{"page":1,"products":[{"name":"Tea","price_cents":450},{"name":"Caf\u00e9 au lait","price_cents":380}]}

Dates and durations

<?nvs
// Shows how `Core\Json::encode` writes dates, durations and time zones.
use Core\Json;
use Core\Time\Date;
use Core\Time\Duration;
use Core\Time\Zone;
// Each value is written as one JSON string.
// This prints `{"day":"2026-05-14","length":"1h30m","zone":"Europe/Vienna"}`.
echo Json::encode([
'day' => Date::fromIso('2026-05-14'),
'length' => Duration::parse('1h30m'),
'zone' => Zone::of('Europe/Vienna'),
]), "\n";
Output
{"day":"2026-05-14","length":"1h30m","zone":"Europe/Vienna"}