CREATE TABLE cust_json_table(
customer_id INT,
customer_info VARIANT -- VARIANT data type which handles the json data
);
-- parse string to json format
SELECT PARSE_JSON(json_col) AS customer_info_json
-- construct JSON object
SELECT OBJECT_CONSTRUCT(
key1,val1,
key2,val2
)
-- Separate the JSON data using colon to access data from column
SELECT
customer_info:field1,
customer_info:field2,
customer_info:field3,
FROM cust_json_table;
-- Separate the nested JSON data using consecutive colon to access data from column
SELECT customer_info:address:street AS street_name
FROM cust_json_table
-- Alternative : Separate the nested JSON data using first colon then consecutive dots to access data from column
SELECT customer_info:address.street AS street_name
FROM cust_json_table
-- Example
WITH dogs_allowed AS (
SELECT *
FROM yelp_business_data
WHERE attributes:DogsAllowed::STRING NOT ILIKE '%None%'
),
touristy_places AS (
SELECT *
FROM yelp_business_data
WHERE attributes:Ambience NOT ILIKE '%None%'
AND attributes:Ambience NOT ILIKE '%u''%'
-- Convert Ambience attribute in the attributes columns into valid JSON using PARSE_JSON.
-- From Valid JSON, fetch the touristy attribute and check if it is true when casted to BOOLEAN.
AND PARSE_JSON(attributes:Ambience):touristy::BOOLEAN = TRUE
)
SELECT
d.business_id,
d.name
FROM dogs_allowed d
JOIN touristy_places t
ON d.business_id = t.business_id