简体   繁体   English

使用Snowflake SQL解析JSON

[英]Parse JSON using Snowflake SQL

I have a JSON object that's written in a weird way. 我有一个以奇怪的方式编写的JSON对象。

> {"custom": [ { "name": "addressIdNum", "valueNum": 12345678},  {
> "name": "cancelledDateAt", "valueAt": "2017-02-30T01:43:04.000Z" }] }

Not sure how to parse something like this. 不知道如何解析这样的事情。 The keys are addressIdNum and cancelledDateAt and the values are 12345678 and 2017-02-30T01:43:04.000Z respectively. 键是addressIdNum和cancelledDateAt,值分别为12345678和2017-02-30T01:43:04.000Z。

How do I parse this using Snowflake SQL? 如何使用Snowflake SQL解析此问题?

Thanks for all your help! 感谢你的帮助!

Best, Preet Rajdeo 最好的,Preet Rajdeo

If your input is ALWAYS in this form (two elements in an array, with the same fields in the same element), you can combine PARSE_JSON function and the path access . 如果您的输入总是以这种形式(数组中的两个元素,在同一元素中具有相同的字段),则可以组合PARSE_JSON函数和路径访问

Just try this: 试试这个:

with input as (
  select parse_json(
    '{"custom": [ { "name": "addressIdNum", "valueNum": 12345678},  {"name": "cancelledDateAt", "valueAt": "2017-02-30T01:43:04.000Z" }] }') 
  as json) 
select json:custom[0].valueNum::integer, json:custom[1].valueAt::timestamp from input;
----------------------------------+-----------------------------------+
 JSON:CUSTOM[0].VALUENUM::INTEGER | JSON:CUSTOM[1].VALUEAT::TIMESTAMP |
----------------------------------+-----------------------------------+
 12345678                         | 2017-03-01 17:43:04               |
----------------------------------+-----------------------------------+

However, if the structure of your data might be different (eg elements in the array might be in a different order), it's probably best to write a JavaScript UDF in Snowflake to convert such messy data into something easier. 但是,如果数据的结构可能不同(例如,数组中的元素可能的顺序不同),最好在Snowflake中编写一个JavaScript UDF,以便将这些混乱的数据转换为更简单的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM