这是有效的JSON(我已经针对两个JSON验证器运行了它,并使用powershell对其进行了解析):
{
"actionCD": "error",
"NotesTXT": ""Exception call timeout""
}
这不是有效的 JSON:
{
"actionCD": "error",
"NotesTXT": "\"Exception call timeout\""
}
但是,parse_json函数在第一个示例中产生失败:
SELECT '{ "actionCD": "error", "NotesTXT": ""Exception call timeout"" }' as json_str
,PARSE_JSON(json_str) as json;
Error parsing JSON: missing comma, pos 38
出乎意料的是,雪花parse_json函数适用于无效的 json:
SELECT '{ "actionCD": "error", "NotesTXT": "\"Exception call timeout\"" }' as json_str
,PARSE_JSON(json_str) as json;
<No Errors>
这让我彻底感到困惑和不确定如何进行。我以编程方式使用 powershell 来创建有效的 JSON,然后尝试使用INSERT INTO ()...SELECT ...
将有效的JSON 插入雪花
这是我尝试在Powershell中构建的插入语句:
INSERT INTO DBNAME.SCHEMANAME.TABLENAME(
RunID
,jsonLogTXT
) SELECT
'$RunID'
,parse_json('$($mylogdata | ConvertTo-Json)')
;
# where $($mylogdata | ConvertTo-Json) outputs valid json, and from time-to-time includes " to escape the double quotes.
# But snowflake fails because snowflake wants \" to escape the double quotes.
这是意料之中的吗?(显然我觉得出乎意料:-))。这里的建议是什么?(我是否应该在 powershell 中搜索我的 json-storage-as-a-string 以查找"并将其替换为 \",然后再将其发送到 snowflake? 不过,这感觉真的很笨拙?
您发布的代码显示了答案:
SELECT '{ "actionCD": "error", "NotesTXT": "\"Exception call timeout\"" }' as json_str
,PARSE_JSON(json_str) as json;
JSON_STR | |
---|---|
{ "NotesTXT": "Exception call timeout", "actionCD | ">: "error" } |
这主要是意料之中的。雪花字符串在 JSON 解析发生之前使用反斜杠作为转义字符。
因此:"\"content\""
将被雪花解析为""content""
,这就是被输入到JSON解析器中的内容,并被视为有效的JSON。
类似的问题可能会出现单引号。
在将发送到雪花之前将其替换为
\
可能会起作用,尽管当我遇到这些类型的问题时,我发现它通常伴随着其他加密/解析错误。例如,我发现更改方法并让雪花解析具有 JSON 的文件通常更合适。这样你就没有额外的转义角色了。不过,这对您的流程来说是一个更大的变化。
Snowflake的文档在这里有一个关于这个主题的快速说明:https://docs.snowflake.com/en/sql-reference/functions-regexp.html#escape-characters-and-caveats