使用VARCHAR从JSON中提取文本

时间:2019-04-18 18:29:26

标签: sql snowflake

尝试使用varchar从带有json的列中提取文本值,但是在模式下运行时,雪花上出现无效的参数错误。这个json与我以前所见的结构有些不同。

尝试过这些以提取文本:

changes:comment:new_value::varchar
changes:new_value::varchar
changes:comment::varchar

JSON看起来像这样:

{
   "comment": 
   { 
      "new_value": "Hello there. Welcome to our facility.", 
      "old_value": ""
   }
}

希望提取此列中的数据,以便输出为:

Hello there. Welcome to our facility.

1 个答案:

答案 0 :(得分:0)

您无法从VARCHAR中提取字段。如果您的字符串是JSON,则必须将其转换为VARIANT类型,例如通过PARSE_JSON函数。

以下示例:

create or replace table x(v varchar) as select * from values('{
   "comment": 
   { 
      "new_value": "Hello there. Welcome to our facility.", 
      "old_value": ""
   }
}');
select v, parse_json(v):comment.new_value::varchar from x;
--------------------------------------------------------------+------------------------------------------+
                              V                               | PARSE_JSON(V):COMMENT.NEW_VALUE::VARCHAR |
--------------------------------------------------------------+------------------------------------------+
 {                                                            | Hello there. Welcome to our facility.    |
    "comment":                                                |                                          |
    {                                                         |                                          |
       "new_value": "Hello there. Welcome to our facility.",  |                                          |
       "old_value": ""                                        |                                          |
    }                                                         |                                          |
 }                                                            |                                          |
--------------------------------------------------------------+------------------------------------------+