I’m trying to parse out some JSON files in snowflake. In this case, I’d like to extract the "gift card" from the line that has "fulfillment_service": "gift_card". I’ve had success querying one dimensional JSON data, but this – with the square brackets – is confounding me.
Here’s my simple query – I’ve created a small table called "TEST_WEEK"
select line_items:fulfillment_service
from TEST_WEEK
, lateral flatten(FULFILLMENTS:line_items) line_items;
Hopefully this isn’t too basic a question. I’m very new with parsing JSON.
Thanks in advance!
Here’s the start of the FULLFILLMENTS field with the info I want to get at.
[
{
"admin_graphql_api_id": "gid://shopify/Fulfillment/2191015870515",
"created_at": "2020-08-10T14:54:38Z",
"id": 2191015870515,
"line_items": [
{
"admin_graphql_api_id": "gid://shopify/LineItem/5050604355635",
"discount_allocations": [],
"fulfillable_quantity": 0,
"fulfillment_service": "gift_card",
"fulfillment_status": "fulfilled",
"gift_card": true,
"grams": 0,
"id": 5050604355635,
"name": "Gift Card - $100.00",
"origin_location": {
"address1": "100 Indian Road",
"address2": "",
"city": "Toronto",
"country_code": "CA",
3
Answers
Those square brackets indicate that you have an array of JSON objects in your
FULLFILLMENTS
field. Unless there is a real need to have an array of objects in one field you should have a look at theSTRIP_OUTER_ARRAY
property of theCOPY
command. An example can be found here in the Snowflake documentation:Maybe you can use two lateral flatten to process values in line_items array:
Sample table:
Sample query:
The output:
In case others are stuck with same data issue (all json data in one array), I have this solution:
With this, you just grab the first element of the array (which is the only element).
If you have nested array elements, just add this to the lateral flatten: