regex 如何在配置单元中提取JSON值

ivqmmu1c  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(112)

我有一个JSON字符串,它存储在DB中与父ID对应的单个单元格中

{"profileState":"ACTIVE","isDefault":"true","joinedOn":"2019-03-24T15:19:52.639Z","profileType":"ADULT","id":"abc","signupDeviceId":"1"}||{"profileState":"ACTIVE","isDefault":"true","joinedOn":"2021-09-05T07:47:00.245Z","imageId":"19","profileType":"KIDS","name":"Kids","id":"efg","signupDeviceId":"1"}

现在我想使用上面的JSON从中提取id。

Parent ID  |  Profile JSON
1          |  {profile_json} (see above string)

我希望输出如下所示

Parent ID  |  ID
1          |  abc
1          |  efg

现在,我已经尝试了几次迭代来解决这个问题

第一次接近:

select
    get_json_object(p.profile, '$$.id') as id,
    test.parent_id
    
    from (
        select split(
                regexp_replace(
                    regexp_extract(profiles, '^\\[(.+)\\]$$',1),
                '\\}\\,\\{', '\\}\\|\\|\\{'),
                '\\|\\|') as profile_list,
                parent_id ,
                
        from source_table) test
        lateral view explode(test.profile_list) p as profile
)

但是这是返回id列的NULL值,我是不是漏掉了什么。

第二种方法:

with profiles as(
  select        regexp_replace(
                    regexp_extract(profiles, '^\\[(.+)\\]$$',1),
                '\\}\\,\\{', '\\}\\|\\|\\{') as profile_list,
                parent_id
                
        from source_table
)      

SELECT
  get_json_object (t1.profile_list,'$.id')
FROM profiles t1

第二种方法只返回上述JSON字符串的第一个id(abc)。

6qqygrtg

6qqygrtg1#

我试着在apache hive v4中复制这个。
数据类型

+----------------------------------------------------+------------------+
|                    data                    | parent_id  |
+----------------------------------------------------+------------------+
| {"profileState":"ACTIVE","isDefault":"true","joinedOn":"2019-03-24T15:19:52.639Z","profileType":"ADULT","id":"abc","signupDeviceId":"1"}||{"profileState":"ACTIVE","isDefault":"true","joinedOn":"2021-09-05T07:47:00.245Z","imageId":"19","profileType":"KIDS","name":"Kids","id":"efg","signupDeviceId":"1"} | 1.0              |
+----------------------------------------------------+------------------+

Sql语言

select pid,get_json_object(expl_jid,'$.id') json_id from 
(select  parent_id pid,split(data,'\\|\\|') jid  from tabl1)a 
lateral view explode(jid) exp_tab as expl_jid;

+------+----------+
| pid  | json_id  |
+------+----------+
| 1.0  | abc      |
| 1.0  | efg      |
+------+----------+

相关问题