简体   繁体   中英

How to check empty JSON in snowflake

I have json as below in a variant column(payload) in snowflake table.

{
    "Input1": {
        "address": "",
        "phone": "123-345-6789",
        "city": "",
        "class": "",
        "name": "test",
        "no_call": true,
        "state": "",
        "zip": ""
    },
    "Input2": {    
        "person": {}
    }
}

When my person dict is empty in input2 I need to take input1 values and construct my new json object. I am writing code as below.

Code snippet:

query="""
select case when payload:Input2:person::variant !='{}'
then constrcut my object with Input2 values
else constrcut my object with Input1 values end as person_details from {sf_schema}.{sf_table}
""".format_map(conn_dict)
cs.execute(query);

This is the python code through which I am executing query in snowflake. But I am getting below error

ValueError: Format string contains positional fields

My conn_dict is having values of sf_schema and sf_table. The problem comes with this statement. It is considering {} as positional arguement where as I was checking to see if it is empty dictionary or not.

payload:Input2:person::variant !='{}'

I tried escaping the characters but no luck. Can you please help how we can fix this issue.

Not sure about the Python code, but in Snowflake SQL you can check to see if person two is an empty object like this:

create or replace table t1 as select parse_json($$
{
    "Input1": {
        "address": "",
        "phone": "123-345-6789",
        "city": "",
        "class": "",
        "name": "test",
        "no_call": true,
        "state": "",
        "zip": ""
    },
    "Input2": {    
        "person": {}
    }
}$$) as v;

select v:Input2:person = parse_json('{}') as PERSON_MISSING from t1;

Actually, it looks as if it's stringified to compare, so it's not even necessary to use parse_json . If the Python code is getting hung up on the single quotes you can try with alternate string terminators like this:

select v:Input2:person = $${}$$ as PERSON_2_MISSING from t1;

Based on @Greg Pavlik example data set, you can also check if there is an empty object by comparing it to the empty object_construct() .

select 
    v:Input2:person = parse_json('{}') as person_missing,
    v:Input2:person = object_construct() as person_missing_too
from t1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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