Mapping and Transforming Data in Commerce Connector

TABLE OF CONTENTS


Overview

  • Audience: Partner and client integration developers and technical consultants configuring Data Exchanges
  • Where it lives: Data Exchange > mapping (stored as YAML) for each step, plus the Global Mapper

Mapping turns the source system's data into the shape Znode or the destination expects. This guide covers the mapping syntax, every built-in function, step chaining, variables and pagination, and shows worked recipes for the transformations partners and clients need most. It also shows where configuration stops and C# should take over.

The short answer

Use mapping expressions for renames, nesting, formatting, defaults and arithmetic. They are visible in Admin, need no deploy and are easy to support.

Move to a custom processor for lookups against other data, conditional logic, splitting or merging records, and anything that needs state across records.

How a Mapping Is Written

Each step has a mapping. The mapping is stored as YAML; you can edit it in Admin, download a sample or upload a file, and you must click Update Mapping to save. Each entry is a destination key and an expression that reads from a step's data.

Data flows left to right from Step 0 (event payload or request body) to Step 1 (call source, map response), Step 2 (uses Step 1 output), the Global mapper (shapes the final output) and the Destination (Znode Import, API, or caller), with example mapping expressions for rename, clean up, default, format and variables

Figure 1. How data moves through steps, mappings and the Global Mapper

ElementSyntaxExample
Read a field from a step{{$StepN.path}}{{$Step1.data[].orderNumber}}
Read from the event or request (Step 0)Step0.Payload.FieldStep1.SKU = Step0.Payload.SKU
Iterate an array[] after the array name{{$Step1.data[].customer.email}}
Nested destinationDotted destination keyorder.customer.name
Function{{ Function(args) }}{{ Upper($Step1.data[].sku) }}
Literal valueA constant string"dataAreaId": "usmf"
Global variable{{Var.NAME}}{{Var.CURRENCY_CODE}}
SecretSee "Check against your build" below{{Secret.API_KEY}}

Mapping: direct property mapping (from the Znode KB)

{

 "OrderNumber": "{{$Step1.data[].orderNumber}}",

 "LinkedOrderNumber": "{{$Step1.data[].linkedOrderNumber}}",

 "Status": "{{$Step1.data[].status}}",

 "StatusCode": "{{$Step1.data[].statusCode}}",

 "OrderDate": "{{$Step1.data[].orderDate}}",

 "CustomerId": "{{$Step1.data[].customer.customerId}}",

 "CustomerEmail": "{{$Step1.data[].customer.email}}"

}

Mapping: nested destination, constants and functions (KB example, corrected)

{

 "dataAreaId": "usmf",

 "order.orderNumber": "{{ $Step1.data[].classNumber }}",

 "order.orderDate": "{{ FormatDate($Step1.data[].orderDate, "yyyy-MM-dd") }}",

 "order.status.status": "{{ $Step1.data[].classStatus }}",

 "order.customer.name": "{{ $Step1.data[].customerName }}",

 "order.customer.email": "{{ $Step1.data[].customerEmailId }}",

 "order.customer.nameAndEmail": "{{ Concat($Step1.data[].customerName, " ", $Step1.data[].customerEmailId) }}",

 "order.customer.totalWithCurrency": "{{ Concat("$", $Step1.data[].total) }}"

}

Built-In Functions

Function names are case-insensitive. Functions can be nested, e.g. Upper(Trim(x)).

GroupFunctionWhat it doesExample
TextUpper(v), Lower(v)Change caseUpper($Step1.data[].sku)
TextTrim(v)Remove leading and trailing spacesTrim($Step1.data[].name)
TextConcat(a, b, …)Join valuesConcat($Step1.data[].first, " ", $Step1.data[].last)
TextReplace(t, old, new)Replace textReplace($Step1.data[].sku, "-", "")
TextSubstring(t, start[, len])Part of a stringSubstring($Step1.data[].zip, 0, 5)
TextLeft(t, n), Right(t, n)First or last n charactersLeft($Step1.data[].desc, 100)
TextLength(v)Length of a valueLength($Step1.data[].sku)
DateDateTime.Today(), DateTime.Now(), DateTime.UtcNow()Current date or timeDateTime.UtcNow()
DateFormatDate(d, fmt)Format a date (.NET format strings)FormatDate($Step1.data[].date, "yyyy-MM-dd")
NumberMath.Round(v[, digits])RoundMath.Round($Step1.data[].price, 2)
NumberMath.Max, Math.MinLargest or smallest of severalMath.Max($Step1.data[].qty, 0)
NumberMath.Abs, Math.Ceiling, Math.FloorAbsolute, round up, round downMath.Floor($Step1.data[].qty)
NullCoalesce(a, b, …)First non-empty valueCoalesce($Step1.data[].webName, $Step1.data[].name)
NullIsNull(v)Test for emptyIsNull($Step1.data[].email)
IdGuid(), Guid.NewGuid()New unique identifierGuid()

No If, lookup, Split or aggregate functions are documented in the KB. Treat those needs as custom-processor work (section 6).

Transformation Recipes

Each recipe shows the source shape, the mapping and the result. Field names on the source side are examples; replace them with your system's.

Rename and flatten a nested ERP item

{ "data": [

 { "number": "LBL-1001", "description": " Hazard label, 4x4 ",

 "inventory": { "uom": "EA", "weightKg": 0.012 },

 "status": { "blocked": false, "webVisible": true } } ] }

Mapping

{

 "SKU": "{{ Upper(Trim($Step1.data[].number)) }}",

 "ProductCode": "{{ Upper(Trim($Step1.data[].number)) }}",

 "ProductName": "{{ Trim($Step1.data[].description) }}",

 "Weight": "{{ Math.Round($Step1.data[].inventory.weightKg, 3) }}",

 "IsActive": "{{ $Step1.data[].status.webVisible }}"

}

Result

SKU,ProductCode,ProductName,Weight,IsActive

LBL-1001,LBL-1001,"Hazard label, 4x4",0.012,true

Defaults and fallbacks

{

 "ProductName": "{{ Coalesce($Step1.data[].webTitle, $Step1.data[].description, $Step1.data[].number) }}",

 "ShortDescription": "{{ Left(Coalesce($Step1.data[].shortText, $Step1.data[].description), 250) }}",

 "Currency": "{{Var.CURRENCY_CODE}}"

}

Dates and time zones

Convert source dates to the format the destination expects. For delta queries, build the filter from the run time:

{

 "OrderDate": "{{ FormatDate($Step1.data[].orderDate, "yyyy-MM-dd") }}",

 "RequestedShip": "{{ FormatDate($Step1.data[].shipDate, "yyyy-MM-ddTHH:mm:ssZ") }}",

 "ImportedOn": "{{ DateTime.UtcNow() }}"

}

Keep all timestamps in UTC between systems. Convert only for display.

Price arithmetic and rounding

{

 "SKU": "{{ $Step1.data[].itemNo }}",

 "RetailPrice": "{{ Math.Round($Step1.data[].unitPrice, 2) }}",

 "TierQty": "{{ Math.Max(Math.Floor($Step1.data[].minQty), 1) }}"

}

Chain steps: look up, then use the result

Multi-step exchanges let a later step use an earlier step's output. Typical case: an inventory event gives a SKU; step 1 asks the ERP for quantity; step 2 writes it.

Step 1 request: GET {{Var.ERP_BASE_URL}}/items/{{Step0.Payload.SKU}}/availability

Step 1 mapping: Step1.SKU = Step0.Payload.SKU

Step 2 mapping: Step2.SKU : Step1.ProductSKU

 Step2.QuantityAvailable : Step1.InventoryQuantity

Global mapper: (prefix Step3, i.e. last step number + 1) shapes the final response

Build URLs, headers and pages from data

Endpoint {{Var.API_BASE_URL}}/v2/orders/{{Step1.OrderId}}

Query parameter orderId = {{Step1.OrderNumber}}

Header Authorization: Bearer {{Step1.Token}}

Header X-Customer-Id: {{Step1.CustomerId}}

Pagination IndexParams.Value = {{Step1.PageNumber}}

 SizeParams.Value = {{Step1.RecordsPerPage}}

SFTP path /inbox/{{Var.TENANT_ID}}/data.csv

Request body {"api_key":"{{Secret.API_KEY}}"}

Pagination is not supported inside multi-step flows; use it on two-step exchanges or inside a custom processor.

Mapping to Znode Import

When the destination is Znode Import, pick the import type (Product, Pricing, Inventory, Category, Customer, Promotion, Brands). Znode pre-fills the destination side; you map the source fields to it. For the default product template the destination includes:

GroupDestination attributes
IdentityProductName, ProductCode, ProductType, SKU, IsActive, Brand
ContentShortDescription, LongDescription, FeatureDescription, ProductSpecification, Tags
MediaProductImage, GalleryImages
MerchandisingIsFeatured, NewProduct, CallForPricing, Color
ShippingWeight, Height, Width, Length, FreeShipping, ShippingCostRules, ShippingInformation
OrderingMinimumQuantity, MaximumQuantity, OutOfStockOptions

Attribute list from the Znode KB (F&SCM native exchange, Default Product Template). Custom attributes in your product family appear as additional columns.

Mapping checklist for imports

  • Map every required column of the template; the import rejects rows without them.
  • Send booleans as true/false and numbers without currency symbols or thousands separators.
  • Make SKU the same value on every import type so products, prices and inventory join.
  • For configurable products, build variant SKUs consistently (e.g. parent number + color + size) and map the parent relationship.
  • Check the Import Logs after the first run; they exist only when the Znode Import step succeeded.

Transforming in a Custom Processor

When expressions are not enough, a custom processor in Custom.Libraries.DataExchange can reshape data between reading and writing. Two patterns exist.

Pattern A: ProcessData with input and output handlers

Used by the samples shipped in the Custom API SDK. The input handler runs the source side of the exchange; your code changes the parsed data; the output handler runs the destination side.

public class NormalizeProductFeed

{

 private readonly IHandlerClient _cc;

 private readonly IZnodeLogging _log;

 private readonly IServiceProvider _sp;

 private readonly int _logId;

 

 public NormalizeProductFeed(IHandlerClient cc, IZnodeLogging log, IServiceProvider sp, int logId)

 { _cc = cc; _log = log; _sp = sp; _logId = logId; }

 

 public async Task<dynamic> ProcessData()

 {

 const string code = "ProductImportNormalized"; // Exchange Code configured in Admin

 

 var input = await _cc.PostInputHandlerAsync(new HandlerRequestModel

 {

 ErpExchangeCode = code, ErpExchangeName = code,

 WebHeaderCollection = new Dictionary<string, string>(), LogId = _logId

 });

 if (input?.Response is null) return false;

 

 string csv = Transform((string)input.Response); // your rules here

 

 var output = await _cc.PostOutputHandlerAsync(new HandlerRequestModel

 {

 ErpExchangeCode = code, ErpExchangeName = code,

 ParsedInputData = csv,

 WebHeaderCollection = new Dictionary<string, string>(), LogId = _logId

 });

 return output?.Response;

 }

 

 internal static string Transform(string csv)

 {

 // Example rules: drop blocked items, upper-case SKUs, convert grams to kg.

 var lines = csv.Split('\n', StringSplitOptions.RemoveEmptyEntries);

 var header = lines[0];

 var rows = lines.Skip(1)

 .Select(l => l.Split(','))

 .Where(c => c[4] != "true") // Blocked column

 .Select(c => { c[0] = c[0].Trim().ToUpperInvariant();

 c[3] = (decimal.Parse(c[3], CultureInfo.InvariantCulture) / 1000m)

 .ToString(CultureInfo.InvariantCulture);

 return string.Join(',', c); });

 return string.Join('\n', new[] { header }.Concat(rows));

 }

}

Use a real CSV parser (e.g. CsvHelper) in production; split-on-comma is for illustration.

Pattern B: step hooks (IBaseProcessor)

The Custom Processor Developer Guide describes IBaseProcessor (namespace Znode.Libraries.CommerceConnector.SDK) with hooks before and after each step. Signatures as described in the KB:

public class EnrichOrderProcessor : IBaseProcessor

{

 private readonly IZnodeLogging _log;

 public EnrichOrderProcessor(IServiceProvider sp) => _log = sp.GetService<IZnodeLogging>();

 

 public Task BeforeStepAsync(List<TransmissionStepModel> context,

 TransmissionStepModel step,

 List<TransmissionStepExecutionOutput> executionOutputs)

 => Task.CompletedTask;

 

 public Task AfterStepAsync(List<TransmissionStepModel> context,

 TransmissionStepModel step,

 List<TransmissionStepExecutionOutput> executionOutputs)

 {

 if (step.StepCode != "Step1") return Task.CompletedTask;

 

 var output = executionOutputs.Single(o => o.StepCode == step.StepCode);

 // output.OutputData holds the step result (format in output.DataFormat).

 output.OutputData = AddWarehouseCodes(output.OutputData);

 _log.LogMessage("Step1 enriched with warehouse codes", nameof(EnrichOrderProcessor), TraceLevel.Info);

 return Task.CompletedTask;

 }

}

Transformations That Need Code

These come up on almost every project. Each sample is plain C# you can call from a processor or connector service.

Lookup table (code translation)

Translate ERP codes (UOM, country, warehouse, price group) to Znode codes. Keep the table in a Znode custom table or a Credential Vault variable so it can change without a deploy.

private static readonly IReadOnlyDictionary<string, string> UomMap =

 new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)

 { ["EA"] = "Each", ["PK"] = "Pack", ["RL"] = "Roll", ["CS"] = "Case" };

 

static string MapUom(string erpUom) =>

 UomMap.TryGetValue(erpUom?.Trim() ?? "", out var z) ? z

 : throw new InvalidOperationException($"No Znode UOM for ERP code '{erpUom}'.");

Conditional mapping

bool isActive = item.VisibleInWebshop && !item.Blocked && !item.SalesBlocked;

 

string outOfStock = item.IsDropShip ? "AllowBackOrdering"

 : item.IsDiscontinued ? "DisablePurchasing"

 : "DontTrackInventory";

Split one source row into many

ERP price rows with minimum quantities become a Znode base price plus tier ranges. The reference implementation derives each tier's maximum from the next tier's minimum:

const decimal LastTierMaximum = 2_147_483_647m;

 

foreach (var skuGroup in rows.Where(r => r.MinimumQuantity > 1)

 .GroupBy(r => r.Sku.Trim(), StringComparer.OrdinalIgnoreCase))

{

 var tiers = skuGroup.OrderBy(r => r.MinimumQuantity).ToArray();

 for (var i = 0; i < tiers.Length; i++)

 {

 var max = i + 1 < tiers.Length ? tiers[i + 1].MinimumQuantity - 1m : LastTierMaximum;

 desired.Add(new ZnodePricingTierModel

 {

 PriceListId = priceListId, SKU = tiers[i].Sku.Trim(), Price = tiers[i].Price,

 Quantity = tiers[i].MinimumQuantity,

 MinQuantity = tiers[i].MinimumQuantity, MaxQuantity = max

 });

 }

}

Merge many source rows into one

var inventoryRows = erpBins

 .GroupBy(b => (Sku: b.ItemNo.Trim().ToUpperInvariant(), Wh: b.LocationCode))

 .Select(g => new { g.Key.Sku, WarehouseCode = MapWarehouse(g.Key.Wh),

 Quantity = Math.Max(0, g.Sum(b => b.QtyAvailable)) });

Validate and de-duplicate before writing

Reject data Znode cannot represent instead of writing half of it. From the reference pricing sync:

if (string.IsNullOrWhiteSpace(row.Sku)) throw new InvalidOperationException("Price row has no item number.");

if (row.MinimumQuantity <= 0) throw new InvalidOperationException($"'{row.Sku}': invalid minimum quantity.");

if (row.Price < 0) throw new InvalidOperationException($"'{row.Sku}': negative price.");

if (row.EndDate.Date < row.StartDate.Date) throw new InvalidOperationException($"'{row.Sku}': ends before it starts.");

 

// Drop exact duplicates, then fail on real collisions (same SKU + qty, different price).

normalized = normalized.GroupBy(r => (r.Sku.ToUpperInvariant(), r.MinimumQuantity, r.Price, r.StartDate, r.EndDate))

 .Select(g => g.First()).ToList();

var collision = normalized.GroupBy(r => (r.Sku.ToUpperInvariant(), r.MinimumQuantity))

 .FirstOrDefault(g => g.Count() > 1);

if (collision is not null)

 throw new InvalidOperationException($"Conflicting prices for '{collision.First().Sku}'.");

Configurable attribute mapping

Let business users decide which PIM fields map to which Znode attributes by storing the map in a Znode custom table. The processor reads it at run time, so adding an attribute needs no deploy.

public class PimAttributeMapRow // one row per field in a Znode custom table

{

 public string PimFieldName { get; set; } = ""; // source field, e.g. "Material"

 public string ZnodeAttributeCode { get; set; } = ""; // target attribute, e.g. "LabelMaterial"

 public bool Sync { get; set; } // false = Znode owns the field, do not import

}

 

var map = (await _znodeClient.GetCustomTableData<PimAttributeMapRow>("PimAttributeMapping"))

 .Where(m => m.Sync && !string.IsNullOrWhiteSpace(m.ZnodeAttributeCode))

 .ToDictionary(m => m.PimFieldName, m => m.ZnodeAttributeCode, StringComparer.OrdinalIgnoreCase);

 

var unmapped = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

var values = new List<PIMAttributeCodeValueModel>();

foreach (var field in pimItem.Fields)

{

 if (map.TryGetValue(field.Name, out var code))

 values.Add(new PIMAttributeCodeValueModel { AttributeCode = code, AttributeValues = field.Value });

 else

 unmapped.Add(field.Name); // logged so someone can map it later

}

if (unmapped.Count > 0)

 _log.LogMessage($"Unmapped PIM fields: {string.Join(", ", unmapped)}", "DataExchange", TraceLevel.Warning);

Example content of the custom table:

PimFieldNameZnodeAttributeCodeSync
MaterialLabelMaterialtrue
AdhesiveAdhesiveTypetrue
MarketingTaglineShortDescriptiontrue
InternalNotesfalse

Testing Mappings

  1. Capture real samples. Save a response from each source endpoint (including edge cases: empty arrays, nulls, special characters, very long text).
  2. Run in non-production with the exchange enabled and a manual Run; check History and the step-level request and response on the Dashboard.
  3. Compare row counts in and out. A difference means a filter or an import rejection.
  4. Check the Znode Import Log for rejected rows and column errors.
  5. Spot-check five records end to end in Znode Admin and on the storefront.
  6. Unit-test custom transforms with the captured samples (example below).

[Fact]

public void Transform_drops_blocked_items_and_converts_weight()

{

 var csv = "SKU,Name,UOM,WeightG,Blocked\nlbl-1, Label ,EA,12,false\nlbl-2,Old,EA,5,true";

 

 var result = NormalizeProductFeed.Transform(csv).Split('\n');

 

 Assert.Equal(2, result.Length); // header + 1 row

 Assert.StartsWith("LBL-1,", result[1]);

 Assert.Contains(",0.012,", result[1]);

}

Golden Rules

Do

  • Trim and upper-case keys (SKU, codes) on the way in.
  • Use Coalesce for every optional source field.
  • Keep code tables in configuration, not in code.
  • Name exchanges and steps after the business object (e.g. ProductImportERP).
  • Document each non-obvious expression in the exchange Description.

Don't

  • Put business rules in long nested expressions nobody can read.
  • Format numbers with currency symbols or separators for imports.
  • Rely on source field order in CSV files; map by header name.
  • Convert time zones in the middle of a pipeline.
  • Transform in two places (mapping and processor) for the same field.

Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.