从对象中提取JSON数组(redshift)

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

我需要从嵌套在对象内的数组中提取数据(假设它所在的列是

metadata
)。它看起来像下面这样:

{
    "name": "abc",
    "references": "abc",
    "owners": [
        "xyz", "abc"
    ],
    "groups": ["x", "x"]
}

有时

metadata
字段可能如下所示:

{
    "name": "abc",
    "references": "abc",
    "owners": [
        "xyz", "abc"
    ],
    "groups": ["x"] -- one less value
}

或者这个:

{
    "name": "abc",
    "references": "abc",
    "sources": "abc", -- new column
    "owners": [
        "xyz", "abc"
    ],
    "groups": ["x", "x"]
}

如果有人能给我一些建议,那将非常有帮助!理想情况下,我会将键逆透视到它们自己的列中,而值将是这些列中的数据(作为行)。但我很难弄清楚如何首先解析它

我已经尝试过:

json_extract_path_text(metadata, 'groups') -- returns ["x", "x"]
JSON_EXTRACT_PATH_TEXT(JSON_EXTRACT_ARRAY_ELEMENT_TEXT(model_meta::VARCHAR, 0), 'groups'::VARCHAR) -- returns an error: JSON parsing error, 8001, nvalid json array object {}
arrays json object amazon-redshift dbt
1个回答
0
投票

您的来电倒转:

JSON_EXTRACT_ARRAY_ELEMENT_TEXT(JSON_EXTRACT_PATH_TEXT((metadata, 'groups'), 0)

此代码可能会为您提供更好的方法来执行此操作的想法:

with inputdata as (
    select json_parse('{"name": "abc", "references": "abc", "owners": ["xyz", "abc"], "groups": ["x", "y"]}') as metadata
)
select i.metadata.name, i.metadata.references, o, g
from inputdata i, i.metadata.owners o, i.metadata.groups g
© www.soinside.com 2019 - 2024. All rights reserved.