Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 construct my object with Input2 values
else construct 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 this 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 argument 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.

like image 826
Ameer Avatar asked Dec 18 '25 15:12

Ameer


1 Answers

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;
like image 149
Greg Pavlik Avatar answered Dec 20 '25 10:12

Greg Pavlik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!