在aws athena中转换json

问题描述 投票:0回答:1

我有一个名为

Game
的表,其中有一个
history
jsonb 列。 json 看起来像这样:

{"Games": {"key1": "value1", "key2": value2}}

(值可以是字符串或数字)。 我想将其转换为这种格式的json:

{"Games": "AllGames": [{"key1": ["value1"]}, {"key2": ["value2"}]]}

原始

json
每个键都有一个值,即使原始值是数字,它也会转换为新
json
中包含一个字段的数组,作为字符串。

我在

postgres
中有这个工作代码,对于
history
不为空的情况:

SELECT jsonb_build_object(
        'Games', jsonb_build_object(
                'AllGames', jsonb_agg(
                        jsonb_build_object(
                                key, json_build_array(CASE
                                                          WHEN value::text LIKE '"%"' THEN value
                                                          ELSE (concat('"',value::text,'"'))::jsonb
                            END)
                        )
                                )
               )
                     )
FROM
    (
        SELECT jsonb_each(history::jsonb->'Games').*
        FROM public.Game
    ) sub

但我不知道如何在 Athena 中做到这一点。

尝试改变

json

json postgresql amazon-athena presto trino
1个回答
0
投票

有多种方法可以实现这一目标。几乎所有这些都将使用将 JSON 转换为某种类型(例如 JSON 对象 ->

map(varchar, json)
)并返回的能力。例如使用一些串联(删除一些
map
创建):

WITH dataset(json_str) AS
(
   values ('{"Games": {"key1": "value1", "key2": 1}}')
)

SELECT '{"Games": { "AllGames": '
        || json_format(
          cast(
             map_values(
               transform_values(
                       cast(
                         json_extract(json_str, '$.Games') -- read the inner object as JSON type 
                           as map(varchar, json)
                       ) -- cast it to map
                   , (k,v) -> map(array[k], array[ array[v] ]) -- transform map values to another map
               )
             ) -- read array of transformed map values 
              as json) -- cast it to JSON
           ) -- format JSON to string
        || '}}'
FROM dataset;

输出:

                            _col0                             
--------------------------------------------------------------
 {"Games": { "AllGames": [{"key1":["value1"]},{"key2":[1]}]}} 
© www.soinside.com 2019 - 2024. All rights reserved.