View a markdown version of this page

JSON formatting and parsing functions - Amazon Athena

JSON formatting and parsing functions

Use these functions to parse text as JSON, and to write a document as compact, key-sorted, or indented text.

Two other functions convert the text of a SQL SELECT statement to a JSON parse tree, and convert the tree back to SQL text.

json function

Parses string as JSON and returns it as a JSON value, with the whitespace between the parts of the document removed. Members keep their order, and duplicate keys are kept. Numbers are written in the form that the JSON parser produces, so 1.50 becomes 1.5.

If string is NULL, the result is NULL. If string is not valid JSON, the query fails. json(string) returns the same result as json_extract(string, '$').

Syntax

json(string)

Arguments

The json function takes the following argument:

string

The text to parse as JSON, as a VARCHAR value.

Return type

JSON

Examples

The following SQL query parses a JSON object.

SELECT json('{"a": 1}') AS result

The query returns the following result.

result

{"a":1}

The following SQL query removes the whitespace from a document. The members keep their order.

SELECT json('{ "b": 2, "a": [1, true, null] }') AS result

The query returns the following result.

result

{"b":2,"a":[1,true,null]}

The following SQL query compares two documents that differ only in whitespace. They are equal after json, but not after a cast to JSON, which keeps the text as written.

SELECT json('{"a": 1}') = json( '{ "a" : 1 }' ) AS normalized_equal, CAST( '{"a": 1}' AS JSON ) = CAST('{ "a" : 1 }' AS JSON) AS cast_equal

The query returns the following result.

normalized_equal cast_equal

true

false

Considerations

A call with a number literal, such as json(42), fails. A typed value of another type, such as an INTEGER column, a BOOLEAN value, or a DATE value, is converted to JSON instead of parsed. For example, a DATE value becomes a JSON string. To convert a SQL value of another type to JSON, use to_json.

CAST(string AS JSON) also checks that the text is valid JSON, but it keeps the text as written, whitespace included. Two documents that differ only in whitespace are not equal after a cast. To compare them, use json on both sides.

Differences from Athena engine version 3

Athena engine version 3 uses json_parse(string) to parse text as JSON. DuckDB has no json_parse function. Use json(string) or CAST(string AS JSON) instead.

In Athena engine version 3, CAST(string AS JSON) returns a JSON string that holds the text, so CAST('[1,2]' AS JSON) returns "[1,2]". In DuckDB, the cast checks that the text is valid JSON and returns it as a JSON value, so the result is the array [1,2]. To get a JSON string from text, use to_json(string).

json_deserialize_sql function

Returns the SQL text of the statement in json, which must be the JSON form of a parsed query, as json_serialize_sql returns it. Use the two functions together to see how DuckDB reads a query. The result shows the statement in a standard form, with keywords in uppercase and each operation in parentheses, so you can see the order in which operators apply.

If json is NULL, the result is NULL. If json does not hold a serialized statement, the query fails.

Syntax

json_deserialize_sql(json)

Arguments

The json_deserialize_sql function takes the following argument:

json

The statements to convert back to SQL text, as a JSON value that holds one or more serialized statements, as json_serialize_sql returns them.

Return type

VARCHAR

Examples

The following SQL query serializes a query and converts it back to SQL text. The result puts the addition in parentheses.

SELECT json_deserialize_sql( json_serialize_sql('SELECT 1 + 2') ) AS result

The query returns the following result.

result

SELECT (1 + 2)

The following SQL query shows that multiplication applies before addition, and that keywords come back in uppercase.

SELECT json_deserialize_sql( json_serialize_sql( 'select 1 + 2 * 3 as n, upper(''abc'') as u' ) ) AS result

The query returns the following result.

result

SELECT (1 + (2 * 3)) AS n, upper('abc') AS u

Considerations

json_serialize_sql serializes SELECT statements only. For other statements, it returns an object that describes the error, and json_deserialize_sql fails on that object.

json_normalize function

Returns json as compact text in a standard form. The function sorts the keys of every object, removes whitespace between values, and writes numbers in a standard format. Array elements keep their order, and duplicate keys stay. If json is NULL, the result is NULL.

Two documents that hold the same data with their keys in a different order, or with different spacing, give the same result. Use json_normalize to compare, group, or join JSON documents.

Syntax

json_normalize(json)

Arguments

The json_normalize function takes the following argument:

json

The document to normalize, as a JSON value or a VARCHAR value that holds JSON text.

Return type

VARCHAR

Examples

The following SQL query sorts the keys at every level and removes the spaces. The array keeps its order.

SELECT json_normalize( '{"b": 2, "a": {"d": 1, "c": [3, 1]}}' ) AS result

The query returns the following result.

result

{"a":{"c":[3,1],"d":1},"b":2}

The following SQL query compares two documents that differ only in key order and spacing. They are equal after normalization, but not before.

SELECT json_normalize( '{"b": 2, "a": 1}' ) = json_normalize('{"a":1,"b":2}') AS normalized_equal, CAST( '{"b": 2, "a": 1}' AS JSON ) = CAST('{"a":1,"b":2}' AS JSON) AS raw_equal

The query returns the following result.

normalized_equal raw_equal

true

false

The following SQL query shows how numbers are rewritten. 1.50 becomes 1.5, and 1e2 becomes 100.0.

SELECT json_normalize('{"a": 1.50, "b": 1e2}') AS result

The query returns the following result.

result

{"a":1.5,"b":100.0}

Considerations

The = operator compares JSON values as text, so the same document with a different key order or spacing is not equal. Normalize both sides before you compare them.

Keys are sorted by their byte values, not alphabetically or numerically. Digits sort before uppercase letters, uppercase letters sort before lowercase letters, and the key "10" sorts before "9".

json_pretty function

Returns json as text formatted for reading. Each object member and each array element is on its own line, indented by four spaces for each level of nesting, with a space after each colon. The lines are separated by a line feed, chr(10). An empty array, an empty object, and a single scalar value stay on one line. If json is NULL, the result is NULL.

Syntax

json_pretty(json)

Arguments

The json_pretty function takes the following argument:

json

The document to format, as a JSON value or a VARCHAR value that holds JSON text.

Return type

VARCHAR

Examples

The following SQL query compares the formatted text of a small object with the expected text. The expected text is an opening brace, the member indented by four spaces, and a closing brace, each on its own line.

SELECT json_pretty('{"a": 1}') = '{' || chr(10) || ' "a": 1' || chr(10) || '}' AS is_expected

The query returns the following result.

is_expected

true

The following SQL query counts the lines of the formatted text. Each array element gets its own line, so the result has 7 lines.

SELECT len( string_split( json_pretty('{"a": 1, "b": [1, 2]}'), chr(10) ) ) AS line_count

The query returns the following result.

line_count

7

Considerations

Numbers are written in a standard format, not as they are written in the input. For example, 1.50 becomes 1.5.

json_serialize_sql function

Parses sql, the text of one or more SELECT statements, and returns a JSON object that describes the parse tree. The object has an error member, and when the text parses, a statements array with one parse tree for each statement. The function only parses the text. It does not check that the tables and columns exist, and it does not run the statements.

If the text does not parse, or is not a SELECT statement, the query does not fail. Instead, the result has error set to true and members that describe the problem, such as error_type. If sql is NULL, the result is NULL. To turn a parse tree back into SQL text, use the json_deserialize_sql function.

Syntax

json_serialize_sql(sql [, skip_null := boolean ] [, skip_empty := boolean ] [, skip_default := boolean ] [, format := boolean ])

Arguments

The json_serialize_sql function takes the following arguments:

sql

The text of the SQL statements to parse, as a VARCHAR value.

skip_null

A flag that controls whether the result keeps members whose value is JSON null, as a BOOLEAN value. When it is true, those members are left out of the result. The default is false. This argument is optional.

skip_empty

A flag that controls whether the result keeps members whose value is an empty array or an empty object, as a BOOLEAN value. When it is true, those members are left out of the result. The default is false. This argument is optional.

skip_default

A flag that controls whether the result keeps members that have their default value, as a BOOLEAN value. When it is true, those members are left out of the result. The default is false. This argument is optional.

format

A flag that controls whether the JSON text is indented, as a BOOLEAN value. When it is true, the JSON text is indented over several lines so that it is easier to read. The default is false. This argument is optional.

Return type

JSON

Examples

The following SQL query parses a SELECT statement and returns the type of the top node of its parse tree.

SELECT json_extract_string( json_serialize_sql('SELECT 1 + 2'), '$.statements[0].node.type' ) AS node_type

The query returns the following result.

node_type

SELECT_NODE

The following SQL query parses text that is not complete SQL. The query succeeds, and the result reports a parser error.

SELECT json_extract_string( json_serialize_sql('SELECT 1 +'), '$.error' ) AS has_error, json_extract_string( json_serialize_sql('SELECT 1 +'), '$.error_type' ) AS error_type

The query returns the following result.

has_error error_type

true

parser

The following SQL query leaves out the members that are null or empty, which makes the result shorter.

SELECT length( json_serialize_sql( 'SELECT 1 + 2', skip_null := true, skip_empty := true ) ) < length(json_serialize_sql( 'SELECT 1 + 2' )) AS is_shorter

The query returns the following result.

is_shorter

true

The following SQL query turns the parse tree back into SQL text with json_deserialize_sql. The result is the same query, with parentheses around the expression.

SELECT json_deserialize_sql( json_serialize_sql('SELECT 1 + 2') ) AS result

The query returns the following result.

result

SELECT (1 + 2)

Considerations

Pass skip_null, skip_empty, skip_default, and format as named parameters, with :=. The function does not accept them as positional arguments.

The parse tree is large, even for a short statement. To read one part of it, use a JSON path function such as json_extract_string.