Formatting JSON
Some Actions may accept additional data that needs to be properly formatted as JSON.
These are a few important things to remember when formatting JSON.
- Strings need to be in quotes.
- Your keys should be in quotes.
- Integers, booleans, and null values should not have quotes.
- The last field or item in a list has NO ENDING COMMA.
- An array (or list) of data must be in [ brackets ].
- Your JSON should start and end with { curly braces }.
See the below example for various formatting options:
{
"product": {
"title": "A string in quotes.",
"id": 123123123,
"boolean_field": true,
"a_null_field": null // No comma here!
},
{
"an_array": [
{"value":"a"},
{"value":"b"} // No comma here!
] // No comma here!
}
The json_value Twig Filter
There is also a special filter you can use to ensure that your JSON keys and values are formatted properly. This filter is available in fields that have the Token Browser icon {t} in the top-right corner of the field.
{
"product": {
{{ "id" | json_value(product.id) }},
{{ "title" | json_value("Copy of - " ~ product.title) }},
{{ "body_html" | json_value(product.body_html) }},
{{ "gift_card" | json_value(product.gift_card) }}
}
}
This filter combines adding the key and value into the json_value filter, in the format:
{{ "your_key" | json_value(your_value) }}
This will ensure that the the key and value are JSON encoded properly, whether it's an integer, boolean, or HTML. When using the json_value you do not need to worry about putting quotes around your values.
You can apply additional filters to your JSON value like so:
{{ "title" | json_value(product.title | upcase | truncate(30)) }}