Get specific values from JSON column in Presto

2020-07-30 03:26发布

问题:

I have a table with a JSON column points with one of the rows as:

{"0": 0.2, "1": 1.2, "2": 0.5, "15": 1.2, "20": 0.7}

I want to get the values for keys "1" and "20" and store them as an alias like first and second in a query. What I've done till now is:

SELECT points, k, v from rewards CROSS JOIN UNNEST(SPLIT_TO_MAP(points, ',', ':')) AS m(k,v) where name='John'

But this query gives me all the rows of k, v. How do I select only those two values corresponding to "1" and "20"?

回答1:

JSON_EXTRACT_SCALAR did the trick.

JSON_EXTRACT_SCALAR(points, '$["1"]') AS first_value

JSON_EXTRACT_SCALAR(points, '$["20"]') AS second_value