results key. Read the document in the JSONEachRow format with a table function such as url or file, and expand the array with ARRAY JOIN: every object of the array becomes a row, and its keys become columns.
Example
Save this document asresponse.json:
results array as an array of named tuples:
ARRAY JOIN results produces one row per element of the array. Inside the query, results.id is the id key of the current element. Columns outside the array, such as request_id, are repeated on every row:
Read the response from an HTTP endpoint
The same query works on a live response. Replacefile with the url table function, and pass request headers, such as an authorization token, in headers(...):
URL table engine and run the same SELECT ... ARRAY JOIN results on it. Every SELECT sends a new request:
Insert the rows into a table
UseINSERT ... SELECT with the same ARRAY JOIN. Pass the structure of the array as the third argument of the table function, so that the values are read with the types of your table instead of the inferred Nullable types:
INSERT fails:
SELECT list of an INSERT ... SELECT contains only column names, ClickHouse does not infer the schema from the data. It builds the structure of the table function from the columns of the target table, so the file is read as if it had top-level columns results.id, results.name and results.price, and there is no results column to expand. Either pass the structure as shown above, or add SETTINGS use_structure_from_insertion_table_in_table_functions = 0 to the query. See Using structure from insertion table.
Things to know
- A key that is missing in some of the objects is returned as
NULLwith the inferred schema. ARRAY JOINreturns no row for a document whose array is empty. UseLEFT ARRAY JOINto keep such a document as one row.- If the array is nested deeper, give the full path and an alias:
ARRAY JOIN data.results AS r, then selectr.id,r.name. - If the response is an array at the top level, such as
[{"id": 1}, {"id": 2}],JSONEachRowalready returns one row per object and you do not needARRAY JOIN. - If the objects do not share a fixed set of keys, declare the column as an array of the
JSONtype: pass'results Array(JSON)'as the structure. WithARRAY JOIN results AS r,r.idthen has theDynamictype; cast it where you need a concrete type, for exampler.id::UInt32.