# json

Captures content and parses it as JSON, allowing immediate access to properties. Works like `capture` but automatically converts the content to a JSON object.

```liquid
{% json my_data %}
  {
    "name": "Example",
    "value": 123
  }
{% endjson %}

{% log my_data.name %}
```

#### Syntax

```liquid
{% json variable_name %}
  { JSON content }
{% endjson %}
```

#### Parameters

| Parameter       | Required | Description                                   |
| --------------- | -------- | --------------------------------------------- |
| `variable_name` | Yes      | Name of the variable to store the parsed JSON |

#### How It Works

1. Content between `{% json %}` and `{% endjson %}` is rendered (Liquid variables are interpolated)
2. The resulting string is parsed as JSON
3. The parsed object is assigned to the specified variable
4. Properties can be accessed immediately using dot notation

#### Examples

**Basic JSON object:**

```liquid
{% json config %}
  {
    "enabled": true,
    "max_items": 50,
    "api_version": "2024-01"
  }
{% endjson %}

{% if config.enabled %}
  {% log "Config loaded, max items: " | append: config.max_items %}
{% endif %}
```

**Dynamic JSON with Liquid variables:**

```liquid
{% json order_payload %}
  {
    "order_id": {{ order.id }},
    "customer": {
      "email": "{{ customer.email }}",
      "name": "{{ customer.first_name }} {{ customer.last_name }}"
    },
    "total": {{ order.total_price }},
    "currency": "{{ shop.currency }}"
  }
{% endjson %}

{% log "Payload created for order: " | append: order_payload.order_id %}
```

**Build request body for HTTP call:**

```liquid
{% json request_body %}
  {
    "event": "purchase",
    "properties": {
      "product_ids": {{ line_items | map: "product_id" | json }},
      "total_value": {{ order.total_price }},
      "currency": "{{ order.currency }}"
    },
    "user_id": "{{ customer.id }}"
  }
{% endjson %}

{% json headers %}
  {
    "Content-Type": "application/json",
    "Authorization": "Bearer {{ API_KEY }}"
  }
{% endjson %}

{% http url: "https://api.example.com/events", method: "POST", headers: headers, body: request_body as response %}
```

**Create array of objects:**

```liquid
{% json products_array %}
  [
    {% for item in order.line_items %}
      {
        "sku": "{{ item.sku }}",
        "quantity": {{ item.quantity }},
        "price": {{ item.price }}
      }{% unless forloop.last %},{% endunless %}
    {% endfor %}
  ]
{% endjson %}

{% log "Products count: " | append: products_array.size %}
```

**Nested JSON structure:**

```liquid
{% json webhook_payload %}
  {
    "type": "order.created",
    "timestamp": "{{ 'now' | date: '%Y-%m-%dT%H:%M:%SZ' }}",
    "data": {
      "order": {
        "id": {{ order.id }},
        "name": "{{ order.name }}",
        "line_items": {{ order.line_items | json }}
      },
      "customer": {
        "id": {{ customer.id }},
        "email": "{{ customer.email }}"
      }
    },
    "metadata": {
      "source": "datajet",
      "shop": "{{ shop.domain }}"
    }
  }
{% endjson %}

{% assign customer_email = webhook_payload.data.customer.email %}
```

**Build GraphQL variables:**

```liquid
{% capture query %}
  mutation updateProduct($input: ProductInput!) {
    productUpdate(input: $input) {
      product { id title }
      userErrors { field message }
    }
  }
{% endcapture %}

{% json variables %}
  {
    "input": {
      "id": "gid://shopify/Product/{{ product_id }}",
      "title": "{{ new_title }}",
      "tags": {{ new_tags | json }}
    }
  }
{% endjson %}

{% graphql query: query, variables: variables as result %}
```

**Set function return value:**

```liquid
{% comment %} Inside a function, use 'response' to set return value {% endcomment %}
{% json response %}
  {
    "success": true,
    "data": {
      "processed": {{ items_processed }},
      "errors": []
    }
  }
{% endjson %}

{% return response %}
```

**Conditional JSON content:**

```liquid
{% json notification %}
  {
    "channel": "email",
    "recipient": "{{ customer.email }}",
    "template": "{% if order.total_price > 100 %}vip_order{% else %}standard_order{% endif %}",
    "priority": {% if order.fulfillment_status == "unfulfilled" %}1{% else %}5{% endif %}
  }
{% endjson %}
```

#### Error Handling

If the content is not valid JSON, an error is thrown with the invalid content and parse error message:

```liquid
{% comment %} This will throw an error - missing quotes around value {% endcomment %}
{% json invalid %}
  {
    "key": invalid_value
  }
{% endjson %}
```

Error message will include the problematic JSON and the specific parse error.

#### Notes

* Content is first rendered as Liquid, then parsed as JSON
* Use `| json` filter to safely embed arrays or objects: `{{ my_array | json }}`
* Strings in JSON must be properly quoted with double quotes
* Special characters in string values should be escaped
* Variable names `response` and `return` have special meaning in functions
* Invalid JSON will throw an error - validate your JSON structure
* Use trailing comma handling with `{% unless forloop.last %},{% endunless %}` in loops


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.datajet-app.com/liquid/tags/json.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
