Skip to main content
A REST API often returns a single JSON document in which the records are nested in an array, for example under a 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 as response.json:
Schema inference reads the whole document as one row and the 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. Replace file with the url table function, and pass request headers, such as an authorization token, in headers(...):
To query the endpoint repeatedly, create a table with the 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

Use INSERT ... 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:
Without the explicit structure, this INSERT fails:
When the 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 NULL with the inferred schema.
  • ARRAY JOIN returns no row for a document whose array is empty. Use LEFT ARRAY JOIN to 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 select r.id, r.name.
  • If the response is an array at the top level, such as [{"id": 1}, {"id": 2}], JSONEachRow already returns one row per object and you do not need ARRAY JOIN.
  • If the objects do not share a fixed set of keys, declare the column as an array of the JSON type: pass 'results Array(JSON)' as the structure. With ARRAY JOIN results AS r, r.id then has the Dynamic type; cast it where you need a concrete type, for example r.id::UInt32.