【问题标题】:String Value to JSON Spark SQL字符串值到 JSON Spark SQL
【发布时间】:2023-02-26 05:46:14
【问题描述】:
我的目标:将下面字符串中的数据提取到spark sql中的4列中。我想选择它如下:
select raw.PostingType, raw.AccountRef.name, raw.AccountRef.value, raw.AccountRef.AcctNum
{PostingType=Credit, AccountRef={name=John Doe, value=27, AcctNum=111111}}
我做了什么/我的问题:我试图使用“from_json”函数,当它有一个嵌套的 json 时,我不确定如何使用它。
我的问题:如何将此字符串中的数据提取到单独的列中?
【问题讨论】:
标签:
python
sql
json
apache-spark-sql
databricks-sql
【解决方案1】:
有几种方法可以做到:
- 使用
from_json 函数 (doc) - 您只需为其提供正确的架构。使用以下字符串作为 from_json 函数的第二个参数:'PostingType string, AccountRef struct<name: string, value: int, AcctNum: long>':
with tbl as (
select from_json(raw, 'PostingType string, AccountRef struct<name: string, value: int, AcctNum: long>') as raw
from some_table)
select raw.PostingType, raw.AccountRef.name, raw.AccountRef.value, raw.AccountRef.AcctNum
from tbl
- 使用
get_json_object 函数 (doc) 使用 JSON 路径表达式提取单个片段,如下所示:
select get_json_object(raw, '$.PostingType') as PostingType,
get_json_object(raw, '$.AccountRef'.name) as name,
...
from some_table
- 使用
: 运算符 (doc) 以类似于上例的 JSON 路径表达式提取值。
附言我在 ChatGPT 上试过这个问题,它生成了正确的代码!