tojson
Converts the values of specified fields to a JSON string.
Command properties
| Property | Description |
|---|---|
| Command type | Transforming |
| Required permission | None |
| License usage | N/A |
| Parallel execution | Supported |
| Distributed execution | Not supported |
Syntax
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 code | Message | Description |
|---|---|---|
| 22300 | missing-field | The field list ends with a comma and the next field name is missing |
Runtime errors
| Error code | Message | Description |
|---|---|---|
| - | 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
-
Convert an entire record to JSON
table duration=1h sys_cpu_logs | tojson output=resultConverts all fields of the record to a JSON string and assigns the result to the
resultfield. -
Convert specific fields to JSON
table duration=1h sys_cpu_logs | tojson output=jsonlog _time, lineConverts only the
_timeandlinefields to a JSON string and assigns the result to thejsonlogfield.
Change history
| Target | Introduced in |
|---|---|
The tojson command | Before Sonar 4.0 |
| Raising the nesting depth limit (20 to 200) | 4.0.2609.0 |
| Guaranteeing key order when fields are specified | 4.0.2609.0 |