Arbitrary JSON data.
Any other type (except for bytes
) can be
cast
to and from JSON:
db>
SELECT <json>42;
{'42'}
db>
SELECT <bool>to_json('true');
{true}
Note that a json
value can be cast into a str
only when it is a JSON string. Therefore, while the following will work
as expected:
db>
SELECT <str>to_json('"something"');
{'something'}
The operation below (casting a JSON array of
string ["a", "b", "c"]
to a str) will result in an error:
db>
SELECT <str>to_json('["a", "b", "c"]');
InternalServerError: expected json string, null; got json array
Use the to_json()
and to_str()
functions to dump or parse a json
value to or
from a str
:
db>
SELECT to_json('[1, "a"]');
{'[1, "a"]'}
db>
SELECT to_str(<json>[1, 2]);
{'[1, 2]'}
JSON in EdgeDB is one of the scalar types.
This scalar doesn’t have its own literal and instead can be obtained
by casting a value into json
or by using to_json()
:
db>
SELECT to_json('{"hello": "world"}');
{'{"hello": "world"}'}
db>
SELECT <json>'hello world';
{'"hello world"'}
Anything in EdgeDB can be cast into json
:
db>
SELECT <json>2019;
{'2019'}
db>
SELECT <json>cal::to_local_date(datetime_current(), 'UTC');
{'"2019-04-02"'}
Any Object
can be cast into json
. This
produces the same JSON value as the JSON serialization of that object.
That is, the result is the same as the output of SELECT
expression in JSON mode, including the
type shape.
db> ... ... ... ... ... ...
SELECT <json>(
SELECT schema::Object {
name,
timestamp := cal::to_local_date(
datetime_current(), 'UTC')
}
FILTER .name = 'std::bool');
{'{"name": "std::bool", "timestamp": "2019-04-02"}'}
JSON values can also be cast back into scalars. This casting is symmetrical meaning that if a scalar can be cast into JSON, only that particular JSON type can be cast back into that scalar:
JSON string can be cast into str
. Casting
uuid
and date and time types to JSON results in a JSON
string representing the original value. This means that it is
also possible to cast a JSON string back into these types. The
string value has to be properly formatted (much like in case of
a str
value being cast) or else the cast will raise an
exception.
JSON number can be cast into any of the numeric types
JSON boolean can be cast into bool
JSON null is special since it can be cast into an {}
of any type
JSON array can be cast into any valid EdgeDB array, so it must be homogeneous, and must not contain null
A regular
tuple
is converted into a JSON array when cast
into json
, whereas a named
tuple
is converted
into a JSON object. These casts are not reversible, i.e. it is not
possible to cast a JSON value directly into a tuple
.
Scalar type SDL, DDL, introspection, and JSON functions and operators.