tojson

Converts the values of specified fields to a JSON string.

Command properties

PropertyDescription
Command typeTransforming
Required permissionNone
License usageN/A
Parallel executionSupported
Distributed executionNot supported

Syntax

tojson [output=STR] [FIELD [, FIELD ...]]

Options

output=STR
Name of the output field to store the JSON string (default: _json).

Target

FIELD
Fields to convert to JSON. You can specify multiple fields separated by commas. If omitted, all fields in the record are converted.

Error codes

Parsing errors
Error codeMessageDescription
22300missing-fieldThe field list ends with a comma and the next field name is missing
Runtime errors
Error codeMessageDescription
-Nesting too deep.The JSON nesting depth of the value being converted exceeds the series' limit. The query fails with an error. The limit differs by series — the 5.0 series (through 5.0.2605.2) allows up to 20 levels; the 4.0 series allows up to 200 levels when you run the query through the REST API, and up to 198 levels in the web console depending on the JSON structure.
-argument should be map, object array or collection, [class name]A value is of a type that is not supported — string, number, boolean, timestamp, IP address, UUID, byte array, and so on. The query fails with an error.

Description

The tojson command converts the values of specified fields to a JSON string and assigns the result to the output field. If no fields are specified, all fields in the record are converted to a JSON object.

The result is stored in the field specified by the output option. If output is not specified, the result is stored in the _json field.

When you specify fields, the 4.0 series starting with 4.0.2609.0 generates the JSON object's keys in the order you specify. Nested structures such as maps and arrays inside values can be converted up to 200 levels in that series; exceeding this aborts the query with an error. The 200-level limit applies when you run the query through the REST API. When you run the query in the web console, the limit is applied more strictly while the result is displayed, so only up to 198 levels are supported depending on the JSON structure.

Examples

  1. Convert an entire record to JSON

    table duration=1h sys_cpu_logs | tojson output=result
    

    Converts all fields of the record to a JSON string and assigns the result to the result field.

  2. Convert specific fields to JSON

    table duration=1h sys_cpu_logs | tojson output=jsonlog _time, line
    

    Converts only the _time and line fields to a JSON string and assigns the result to the jsonlog field.

Change history

TargetIntroduced in
The tojson commandBefore Sonar 4.0
Raising the nesting depth limit (20 to 200)4.0.2609.0
Guaranteeing key order when fields are specified4.0.2609.0