# Test your JSONata mapping locally

**Run a JSONata expression against a sample feed entry on your machine before you add it to a data mapping in AI Hub.**

Testing an expression locally shows you the exact value it returns for a given product variant, so you can fix errors before they reach the product feed. This page uses a small Node.js script with the open source [`jsonata`](https://www.npmjs.com/package/jsonata) library.

The local setup approximates the AI Hub runtime. The bindings you create on this page are stand-ins for the default bindings that AI Hub adds to a data mapping, so results can differ from the real implementations. Confirm the final mapping by exporting your product data in AI Hub.

For the feed entry structure, the available bindings, and example expressions, see [JSONata data mapping](/agentic-commerce/ai-hub/jsonata-data-mapping.md).

## Prerequisites

- [Node.js](https://nodejs.org/) and npm installed on your machine.
- A terminal and a text editor.

## Set up a test folder

Create a folder for the test files and install the `jsonata` library:

```bash title="Install JSONata"
mkdir jsonata-test
cd jsonata-test
npm init -y
npm install jsonata
```

## Create a feed entry

Each expression runs against one feed entry, which represents a single product variant. Save the following example as `feed-entry.json` in the test folder.

```json title="feed-entry.json"
{
  "productData": {
    "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "name": { "en-US": "Classic Running Shoe", "de-DE": "Klassischer Laufschuh" },
    "description": { "en-US": "A versatile everyday running shoe." },
    "slug": { "en-US": "classic-running-shoe" },
    "masterVariant": {
      "id": 1,
      "key": "classic-running-shoe-master",
      "sku": "CRS-001-BLK-42"
    },
    "variants": [
      {
        "id": 2,
        "key": "classic-running-shoe-v2",
        "sku": "CRS-001-BLK-43"
      }
    ]
  },
  "variant": {
    "id": 1,
    "key": "classic-running-shoe-master",
    "sku": "CRS-001-BLK-42",
    "price": {
      "id": "a1b2c3d4-5678-4abc-b3fc-2c963f66afa6",
      "value": { "type": "centPrecision", "centAmount": 12999, "currencyCode": "USD", "fractionDigits": 2 }
    },
    "attributes": [
      { "name": "color", "value": "black" },
      { "name": "size", "value": 42 }
    ],
    "availability": {
      "channels": {
        "inventory-channel-id": {
          "isOnStock": true,
          "availableQuantity": 100
        }
      }
    }
  },
  "store": { "id": "store-ABC" },
  "shippingMethods": [{ "id": "sm-standard" }, { "id": "sm-express" }]
}
```

The `availability.channels` object is keyed by inventory Channel ID. `"inventory-channel-id"` is a placeholder key in this sample. Your feed entries can also have no `availability` at all, for example when the variant has no inventory entry.

To test with your own data, build a feed entry from a real product:

1. Get the [ProductProjection](/search.md?urn=ctp:api:type:ProductProjection) for the product in the Store that your Agentic Channel uses, and set it as `productData`.
2. Choose one [Product Variant](/search.md?urn=ctp:api:type:ProductVariant) and set it as `variant`. To get the scoped `price` field on the variant, resolve the projection with `priceCurrency` and the price selection inputs that your Agentic Channel uses, such as `priceCountry` and `priceChannel`. A Store alone filters the `prices` array but doesn't set `price`.
3. Set `store` to the [Store](/search.md?urn=ctp:api:type:Store) and `shippingMethods` to the [Shipping Methods](/search.md?urn=ctp:api:type:ShippingMethod) that apply.

A raw API response for a product isn't a feed entry. Wrap the data in the four top-level fields `productData`, `variant`, `store`, and `shippingMethods`, or your expressions fail to find the values.

## Add stand-ins for bindings

AI Hub adds default bindings to every data mapping: the variables `$country`, `$locale`, and `$storeKey`, and the functions `$tail`, `$getAttribute`, `$storeBaseUrl`, `$priceToAmount`, and `$formatPrice`. You can see them in the **Bindings** section of the **Product sync** tab. These don't exist outside AI Hub, so create stand-ins for the ones you use. Save the following as `bindings.js`.

```javascript title="bindings.js"
// Local stand-ins that mirror the default bindings in AI Hub.
const variables = {
  country: 'US',
  locale: 'en-US',
  storeKey: 'my-store',
};

const functions = {
  tail: (arr) => (Array.isArray(arr) ? arr.slice(1) : []),
  getAttribute: (attributes, name) =>
    (attributes || []).find((attribute) => attribute.name === name)?.value,
  // Takes the price value object, for example variant.price.value
  priceToAmount: (value) => {
    if (!value) return '';
    const digits = value.fractionDigits;
    return value.type === 'centPrecision'
      ? value.centAmount / 10 ** digits
      : value.preciseAmount / 10 ** digits;
  },
  // Takes the amount from $priceToAmount and the same price value object
  formatPrice: (amount, value) =>
    typeof amount === 'number' && value ? `${amount.toFixed(value.fractionDigits)} ${value.currencyCode}` : '',
};

module.exports = { variables, functions };
```

Change the values in `variables` to match the bindings in your channel. The functions take the price value object, not the whole price. Chain them like the default mapping does, for example `$priceToAmount(variant.price.value) ~> $formatPrice(variant.price.value)`.

## Run an expression

Save the following script as `test.js`. It loads the feed entry, registers the bindings, and evaluates the expression you pass as a command-line argument.

```javascript title="test.js"
const fs = require('fs');
const jsonata = require('jsonata');
const { variables, functions } = require('./bindings');

const expressionText = process.argv[2];
const entry = JSON.parse(fs.readFileSync('feed-entry.json', 'utf8'));

(async () => {
  const expression = jsonata(expressionText);
  for (const [name, fn] of Object.entries(functions)) {
    expression.registerFunction(name, fn);
  }
  const result = await expression.evaluate(entry, variables);
  console.log(JSON.stringify(result));
})();
```

Run an expression and wrap it in single quotes so your shell doesn't change it:

```bash title="Run an expression"
node test.js '$lookup(productData.name, $locale)'
```

The script prints the result:

```text title="Output"
"Classic Running Shoe"
```

Try the other expressions from [JSONata data mapping](/agentic-commerce/ai-hub/jsonata-data-mapping.md#expression-examples) the same way. For example, this expression builds a title from the name and attributes:

```bash title="Build a composite title"
node test.js '$lookup(productData.name, $locale) & " - " & $getAttribute(variant.attributes, "color") & " / " & $string($getAttribute(variant.attributes, "size"))'
```

```text title="Output"
"Classic Running Shoe - black / 42"
```

Attribute values can be localized objects, such as `{ "en-US": "Black" }`, or plain values. This expression returns the configured locale when the attribute is localized and otherwise returns the value as-is:

```bash title="Get a localized or plain attribute"
node test.js '($value := $getAttribute(variant.attributes, "color"); $type($value) = "object" ? $lookup($value, $locale) : $value)'
```

## Check for missing values

If an expression returns no value, this local script prints `undefined`. A tested real feed entry for SKU `12345` has an empty `attributes` array, so it has no `material` attribute. Load that entry as `feed-entry.json` to reproduce the lookup:

```bash title="Look up a missing attribute"
node test.js '$getAttribute(variant.attributes, "material")'
```

```text title="Output"
undefined
```

In AI Hub, an expression that returns no value produces an empty cell for that field in the exported product data. The product is still exported. An expression that throws an error stops the export instead, as described in [Check for errors](/agentic-commerce/ai-hub/jsonata-test-locally.md#check-for-errors).

To provide a fallback, test the value with `$exists` in a conditional expression:

```bash title="Add a fallback value"
node test.js '$exists($getAttribute(variant.attributes, "material")) ? $getAttribute(variant.attributes, "material") : "not specified"'
```

```text title="Output"
"not specified"
```

Test with variants that have missing attributes or no price, because your catalog can contain products that the sample doesn't cover.

## Check for errors

Some missing values cause an error instead of an empty result. For example, a variant with a `null` price has no `fractionDigits`, so the manual conversion `variant.price.value.centAmount / $power(10, variant.price.value.fractionDigits)` throws an error. Guard the price first:

```bash title="Guard against a missing price"
node test.js 'variant.price ? $priceToAmount(variant.price.value) ~> $formatPrice(variant.price.value) : ""'
```

If an expression can't be evaluated when you export product data, AI Hub shows an **Export failed** message with the function name and the SKU of the variant it failed on, for example `Argument 2 of function "power" does not match function signature`. Select **Open data mapping**, fix the expression, and export again. Whether a required field that is empty causes problems depends on the provider. Check the requirements on the provider's product data page.

## Validate the mapping in AI Hub

The local script approximates AI Hub, so export your product data from AI Hub as a final check. The export evaluates every expression in the mapping against your real products. AI Hub has no preview for a single feed entry or product, so the exported CSV file is the way to see the mapped output.

> **Warning:** The following steps save an empty value and an expression that fails every export. Saving applies your changes to a connected channel after a short redeploy, and AI Hub has no preview or dry run, so a failing expression goes live as saved. Switching off the sync toggles stops the feeds but doesn't make a test safe. Use a test channel that isn't connected to a provider, and restore your expression in the last step.

1. In the Merchant Center, open your Agentic Channel and go to the **Product sync** tab.
2. Edit the expression for one field and save the mapping. To see how empty values behave, use an expression that returns nothing for that field, such as `$getAttribute(variant.attributes, "does-not-exist")`.
3. Export the product data for the channel and open the exported CSV file. The field you changed is empty for every variant, and the other columns keep their values.
4. To see how errors behave, change the expression to one that can't be evaluated, such as `$power(10, null)`, and export again. The export fails and shows the function name and the SKU of the variant, as described in [Check for errors](/agentic-commerce/ai-hub/jsonata-test-locally.md#check-for-errors).
5. Restore the expression that you want to keep, and export once more to confirm that the export succeeds and the values are correct.

The export shows the values that AI Hub generates. Empty values are exported as empty strings. The export doesn't show how a provider handles them, because providers validate the data on their side and AI Hub doesn't show the results. After a sync, check the provider's dashboard for validation errors, and fix them in your data mapping. For examples, see [Build derived values](/agentic-commerce/ai-hub/jsonata-data-mapping.md#build-derived-values). Check the provider's product data requirements for required fields.

## Next steps

- Draft expressions faster with [Generate a data mapping with AI](/agentic-commerce/ai-hub/jsonata-generate-with-ai.md).
- Look up bindings and the feed entry structure in [JSONata data mapping](/agentic-commerce/ai-hub/jsonata-data-mapping.md).

## Related pages

- [Area overview page with navigation](/agentic-commerce.md)
- [Next page: Generate mapping with AI](/agentic-commerce/ai-hub/jsonata-generate-with-ai.md)
- [Search documentation and API specs](/search.md)