json - Redshift/Postgres : how can I ignore rows that generate errors?(json_extract_path_text 中的无效 JSON)

标签 json amazon-redshift

我尝试在 redshift 中运行查询,我选择使用 json_extract_path_text。遗憾的是,此数据库列中的某些 JSON 条目无效。

发生了什么: 当查询遇到无效的 JSON 值时,它会停止并显示“JSON 解析错误”。

我想要的:忽略该列中任何包含无效 JSON 的行,但返回它可以解析 JSON 的任何行。

为什么我不能让它做我想做的事:我不认为我理解 Redshift/Postgres 中的错误处理。应该可以简单地跳过任何产生错误的行,但我尝试输入 EXEC SQL WHENEVER SQLERROR CONTINUE(基于 the Postgres docs )并在 SQLERROR< 处或附近出现“语法错误”/”。

最佳答案

创建一个 python UDF:

create or replace function f_json_ok(js varchar(65535)) 
returns boolean
immutable
as $$
    if js is None: 
        return None

    import json
    try:
        json.loads(js)
        return True
    except:
        return False
$$ language plpythonu

像这样使用它:

select *
from schema.table
where 'DesiredValue' = 
    case 
        when f_json_ok(json_column) then json_extract_path_text(json_column, 'Key') 
        else 'nope' 
    end 

关于json - Redshift/Postgres : how can I ignore rows that generate errors?(json_extract_path_text 中的无效 JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25317707/

相关文章:

json - 如何在 proxy_pass 中设置内容类型?

json - 注释掉简单 json 中的行以放置一些描述

android - 无法读取解析推送通知包数据

amazon-web-services - 如何通过SQL Workbench将Amazon Redshift输出保存到本地CSV?

maven - Redshift JDBC 驱动程序的 Gradle/Maven 依赖项

sql - 有没有更好的方法通过 Redshift 中的 join 来避免数据倾斜?

r - Redshift 上 Shiny 缓慢

java - 从android应用程序中的php文件读取JSON数据

json - 如何创建一个无限嵌套的 json 并在 go lang 数据结构中访问它?

amazon-web-services - 有没有办法在通过 Glue 插入 Redshift 时简单地截断列?