【问题标题】:Not able to explode json string in hive无法在蜂巢中爆炸 json 字符串
【发布时间】:2021-10-20 11:23:17
【问题描述】:
[{"name":"john","id":12,"location":"delhi"},{"name":"raj","id":18,"location":"mumbai"},{"name":"Rahul","id":14,"location":"hyd"}]

在 hive 表中的一条记录上使用get_json_object 后,我有这个字符串(不是结构)。我需要分解它以创建一个新表,其中列名称为名称、id 和位置。有人可以帮忙吗?

Explode()inline() 接受结构数组。尝试了explode(Array(struct(my get_json_object output))),但它没有给出预期的结果。

【问题讨论】:

  • 在 JSON 的第二个和第三个对象中,键 name 未正确括在双引号中。这有什么不同吗?
  • 对不起。这是在这里发布时的拼写错误。实际数据不存在这个问题

标签: sql arrays json hive hiveql


【解决方案1】:

首先将字符串转换为 JSON 对象数组:删除方括号,用逗号分隔花括号并展开。然后使用带有横向视图的 json_tuple 来提取所有值。看这个演示:

with mytable as (--demo table, use your table instead
select '[{"name":"john","id":12,"location":"delhi"},{"name":"raj","id":18,"location":"mumbai"},{"name":"Rahul","id":14,"location":"hyd"}]' as json_string
)

select --t.json_string as original_string, --commented
      e.pos as position_in_array,
      --values from json
      x.name, x.id, x.location
      
  from mytable t 
      lateral view outer posexplode( split(regexp_replace(json_string,'^\\[|\\]$',''),      --remove []
                          '(?<=\\}),(?=\\{)'  --split by comma only after } and before {
                         )                    --converted to array of json strings
                               )e as pos, json --exploded array element with position
       --extract all from e.json 
      lateral view json_tuple(e.json,'name', 'id', 'location') x as name, id, location

结果:

position_in_array  x.name   x.id    x.location  
0                  john     12      delhi
1                  raj      18      mumbai
2                  Rahul    14      hyd

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 2014-06-10
    • 2023-03-06
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多