I want to create a snippet that allows me to create easily json strings (as a output):
{"dropdown_options":[{"id":1,"label":"Option A"},{"id":2,"label":"Option B"},{"id":3,"label":"Option C"}]}
where it extends with id and label infinitely inside a form that you input in.
Is that possible?
Hey @CuteKitsuneForever_J try out this snippet:
{note}Fill in your dropdown options below. Add as many as you like.{endnote}
{formparagraph: name=Raw Options; default=Option A
Option B
Option C}
{options_list=split(`Raw Options`, "
")}
{"dropdown_options":[{=join(
map(
filter(options_list, v -> trim(v) <> ""),
(v, i) -> concat(
"{\"id\":", i, ",\"label\":\"", replaceregex(trim(v), "\"", "\\\"", "g"), "\"}"
)
),
","
)}]}
You can read more about the various formulas on this page: https://blaze.today/formulas/reference Here's a brief explanation of this snippet:
- Uses a paragraph form field (formparagraph) to let you type one option per line
- Splits the input text into a list by newlines using split()
- Filters out any blank lines with filter() and trim()
- Maps over each option using map(), assigning an auto-incrementing id (starting at 1) and a label from your input
- Escapes any quotes inside your option labels using replaceregex() so the JSON stays valid
- Joins all the generated objects together with commas using join()
- Wraps everything in the final {"dropdown_options":[...]} JSON structure
Let us know if it works for you!