EZ Exporter Calculated Fields - For Loops via List Comprehension
EZ Exporter only supports one-line formulas. "For Loops" can be accomplished in a one-line formula by using a "List Comprehension" syntax (this is a Python programming concept).
Let's look at the formula below as an example:
",".join([i + "abc" for i in to_list({{ tags }})])
The above formula will iterate through a list of of tags and append the characters "abc" to each one. It will then output a string of the new values separated by a "," character.
For example, if the value of the "tags" field is: Alice, Bob, Eve
The formula will output: Aliceabc,Bobabc,Eveabc
Here's a quick breakdown:
- The "tags" field, which is just a comma-separated string of tags is first converted into a "list" (array) object using the to_list() function so we can loop through it.
- Loop though each item in the list (the "i" variable) and append the characters "abc" to it.
- Finally, output the results as a string separated by the comma "," character (this is the
",".join()
part). Simply change the comma to another character to change the separator. For example, to separate the results with the "|" character instead and a space before and after the "|" character, you would use:" | ".join()
. If there's only 1 item/result, then the separator won't apply.
EXAMPLES
Filter a list of tags and only output those that end with "_special".
",".join([i for i in to_list({{ tags }}) if i.endswith("_special")])
This will output something like:
tea_special,coffee_special
Output all line items of an order in a single cell in the format "Lineitem Name: Quantity" separated by a comma and space.
", ".join([i.name + ": " + str(i.quantity) for i in load_json_data({{ line_items }})])
This will output something like:
Prduct A - Blue: 15, Product B - Small: 5, Product C - Yellow: 9
Note here that line_items
is a JSON string and we used the load_json_data() function to convert it to a Python list of dictionary objects.
Output all metafields for each product in the format "Metafield Key: Value" separated by a line break.
"\n".join([i.key + ": " + str(i.value) for i in load_json_data({{ metafields }})])
This will output something like:
expiration_date: 2025-12-31 supplier_sku: 123ABC commission: 12%
Filter the list of successful order transactions to only include those where the "kind" is "capture" or "sale" and return the most recent transaction date.
get_value_by_position(sorted([i.created_at for i in load_json_data({{ transactions.successful_transactions }}) if i.kind in ["capture", "sale"]]), -1)
This formula is more complex, but it basically performs the following steps:
- Filter the list of transactions to only include those where the "kind" attribute is "capture" or "sale".
- Only ouput the value of the "created_at" field.
- Sort the list of the filtered "created_at" values in ascending order.
- Finally, return just the last item in the sorted list (i.e. the highest "created_at" value).
Related Articles:
App: EZ Exporter