clickhousejson-extract

clickhouse extract several values by same key


I have a string which represent array of jsons like '[{json}, {json}...]' in this jsons I have similar keys like metric: '[{"metric": "", }, {"metric": "", }]'. How can I get all values by key "metric" ? If I will use JsonExtract it will return nothing because of repeatable keys in string.

The main point is in a string which represent array of json's objects I have same keys. And I need to get them. As example: '[{"id":"1", "metric":"11"}, {"id":"1", "metric":"12"}]'. So I want to get by key "metric" values 11, 12


Solution

  • Try this:

    SELECT 
      JSONExtractInt (j, 'id') AS id
    , groupArray (JSONExtractInt (j, 'metric')) AS metrics
    FROM
    (
      SELECT arrayJoin (JSONExtractArrayRaw (c1)) AS j
      FROM VALUES 
      (
          ('[{"id":"1", "metric":"11"}, {"id":"1", "metric":"12"}]')
        , ('[{"id":"2", "metric":"21"}, {"id":"2", "metric":"22"}, {"id":"2", "metric":"23"}]')
      )
    )
    GROUP BY id
    
    id metrics
    2 [21,22,23]
    1 [11,12]