---
title: "Sort JsonKeyValueIterator & Numeric Strings in Orchestrate"
description: "Fix the JsonKeyValueType sort build error in Workday Orchestrate loops and convert numeric strings with toNumber() so Employee_IDs sort numerically."
url: https://kiweely.com/guides/workday-orchestrate-sort-jsonkeyvalueiterator-numeric-sorting
---

# Sorting JsonKeyValueIterator Collections and Numeric String Values in Workday Orchestrate Loops

Workday Orchestrate fails at build time when sorting a JsonKeyValueIterator loop by item.key(), and sorts numeric strings lexicographically (‘1’, ‘1000’, ‘3’). Use a two-loop key extraction pattern for JSON objects and cast string IDs with toNumber() in Loop Sort By.

-   **Checked** against Workday on November 6
-   Applies to **Workday Orchestrate**
-   3 min read
-   Published November 6
-   By Kiweely

## Build Failure When Sorting a `JsonKeyValueIterator` Loop by `item.key()`

When iterating over a JSON object’s dynamic key-value pairs using `.jsonKeyValueIterator()` inside a **Loop** component, configuring the loop’s **Sort By** field with `data..item.key()` passes in-editor expression validation (`Validate` reports no issues), but fails during orchestration build with:

text

```
JsonKeyValueType collections can only be sorted by their existing key. The stringKey and numberKey configurations are not supported.
```

Although `item.key()` returns a `String` type per the `JsonKeyValue` member function specification, the Orchestrate compiler rejects `stringKey` and `numberKey` sort configurations on `JsonKeyValueIterator` collections at build time.

### Two-Loop Key Extraction and Fold Pattern for Sorted JSON Objects

Because JSON objects are unordered sets of name-value pairs by specification, only sort object keys when a downstream consumer strictly requires deterministic key ordering. To output a JSON object with its keys sorted alphabetically without triggering the `JsonKeyValueType` build error, separate key extraction from sorting across two **Loop** steps:

1.  **Step 1 — Extract Keys into a `StringList` (`LoopExtractKeys`):**
    
    -   Set **Data Set** to `data.SourcePayload.jsonObject.jsonKeyValueIterator()`.
    -   Do **not** configure **Sort By** on this loop.
    -   Add an **Aggregation** (`KeysList`) using a custom fold or list aggregation that collects `data.LoopExtractKeys.item.key()` into a `StringList`.
2.  **Step 2 — Sort the `StringList` and Rebuild the JSON Object (`LoopBuildSortedJson`):**
    
    -   Set **Data Set** to `data.LoopExtractKeys.KeysList.iterator()`.
    -   Set **Sort By** to `data.LoopBuildSortedJson.item` (which is a standard `String` iterator item and compiles cleanly).
    -   Enable **Force Sequential Processing** in the loop’s advanced settings so keys are appended in exact sorted order.
    -   Inside the loop, look up the value for the current key from the original JSON document and fold each pair into a new JSON object starting from `"{}".asJSON()` using `.addJsonValue(key, value)` or `.addStringValue(key, value)`:

javascript

```
// Initial value in Custom Fold Aggregation (SortedObject):
"{}".asJSON()

// Accumulation expression inside LoopBuildSortedJson:
data.LoopBuildSortedJson.SortedObject.addJsonValue(
  data.LoopBuildSortedJson.item,
  data.SourcePayload.jsonObject.jsonDataAtJsonPath("$." + data.LoopBuildSortedJson.item)
)
```

Because this two-pass fold parses a JSON path for every key sequentially, restrict it to small configuration or metadata objects rather than high-volume transactional arrays.

* * *

## Why Numeric IDs Sort as `"1"`, `"1000"`, `"100000"`, `"3"` in Loops and Text Templates

The **Create Text Template** component does not provide a built-in sorting directive (`{{#each}}` emits items in the exact order yielded by the iterator). To sort JSON array records—such as grouping and ordering employee dependent records by `Employee_ID`—you must sort the collection in a **Loop** component before or after a **Batch Loop**.

However, Workday Orchestrate sorts `String` expressions lexicographically (character code by character code) and `Number` expressions numerically. When `Employee_ID` is stored as a JSON string (`"1"`, `"3"`, `"1000"`, `"100000"`), configuring **Sort By** on the **Loop** step as:

javascript

```
data.LoopEmployees.item.stringAtJsonPath("$.Employee_ID")
```

sorts the records in ASCII lexicographical order:

json

```
[
  { "Employee_ID": "1", "Dependents": [ ... ] },
  { "Employee_ID": "1000", "Dependents": [ ... ] },
  { "Employee_ID": "100000", "Dependents": [ ... ] },
  { "Employee_ID": "3", "Dependents": [ ... ] }
]
```

### Converting String Keys with `.toNumber()` in Loop `Sort By`

To force numerical sorting (`1`, `3`, `1000`, `100000`), convert the extracted string to a `Number` inside the **Loop** component’s **Sort By** expression using `.toNumber()`:

javascript

```
data.LoopEmployees.item.stringAtJsonPath("$.Employee_ID").toNumber()
```

### Handling Alphanumeric IDs with `includeCharactersUsingList`

If `Employee_ID` values contain prefixes or formatting characters (such as `"EMP-001000"` or `"CW_3"`) that would cause `.toNumber()` to throw an exception on non-numeric characters, strip non-digit characters first using `.includeCharactersUsingList(inclusionList, defaultReplacement)`.

A common mistake when calling `includeCharactersUsingList` is passing full ID strings into `inclusionList`. `includeCharactersUsingList` evaluates the input string **one character at a time** and retains only characters present in the `StringList`. Pass the ten individual ASCII digit characters (`"0"` through `"9"`) and an empty string `""` as the replacement before calling `.toNumber()`:

javascript

```
data.LoopEmployees.item
  .stringAtJsonPath("$.Employee_ID")
  .includeCharactersUsingList(
    list.stringList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"),
    ""
  )
  .defaultIfEmpty("0")
  .toNumber()
```

* * *

## Verifying the Sort Order in Your Tenant

1.  Open the orchestration in **Orchestration Builder** and click **Validate** and save to confirm the **Loop** step builds without the `JsonKeyValueType collections can only be sorted by their existing key` error.
2.  Run the orchestration in **DebugOrchestrations** mode with test records containing `Employee_ID` values `"1"`, `"1000"`, `"100000"`, and `"3"`.
3.  Inspect the **Loop** aggregation output in the debug panel and verify that the emitted array order is `"1"`, `"3"`, `"1000"`, `"100000"`.

## Sources checked

-   [Reference: Loop](https://developer.workday.com/documentation/GUID-be61fde3-f1e0-465f-95a2-004a7caae995)
-   [Reference: JsonKeyValue Member Functions](https://developer.workday.com/documentation/GUID-4cea2088-1bee-41fd-8730-2d5910c99dc0)
-   [Reference: Json Member Functions](https://developer.workday.com/documentation/GUID-85d61153-4a66-41e7-ad4f-921b0e9a152e)
-   [Reference: String Member Functions](https://developer.workday.com/documentation/GUID-c22f5c68-87f5-4bd6-ad96-4e0d246e72c3)
-   [Concept: Text Templates](https://developer.workday.com/documentation/GUID-e2785ee9-6d55-4f43-b375-a2e546da6503)

## Related guides

[All guides](https://kiweely.com/guides)

-   [### Generating UUIDs with random.randomUUID() and Fixing stringAtJsonPath().toNumber() in Orchestrate Workday Orchestrate uses random.randomUUID() instead of PMD’s UUID() function to generate unique batch IDs, and requires chaining .toNumber() on the outer stringAtJsonPath() function rather than inside the JSONPath literal.](https://kiweely.com/guides/workday-orchestrate-randomuuid-stringatjsonpath-tonumber)
-   [### JSONPath Logical Filter Expressions and Wildcard XPaths in Workday Orchestrate Compound JSONPath filter expressions (&&, ||) in Workday Orchestrate fail silently when typographic quotes are pasted or unsupported filter tokens are chained. Learn the supported JSONPath and wildcard XPath syntax and when to replace SOAP launch polling with Trigger Integration.](https://kiweely.com/guides/workday-orchestrate-jsonpath-logical-filters-xpath-wildcards)
-   [### Why Log to File Turns XML Closing Tags into <// and How to Write #if Conditions in CreateTextTemplate Viewing aggregated XML through a Log to File step in Workday Orchestrate turns every closing tag ‘</’ into ‘<//’ because Log to File defaults its CSV escape character to ‘/’. Use Store Document for XML files, and omit outer parentheses around #if conditions in CreateTextTemplate.](https://kiweely.com/guides/workday-orchestrate-xml-double-slash-log-to-file-if-conditions)
-   [### Why stripHtmlTags and htmlToPlainText Leave HTML Tags Over 2,003 Characters in Workday Orchestrate In Workday Orchestrate, stripHtmlTags and htmlToPlainText can silently leave individual HTML tags of 2,003 or more characters—such as inline base64 <img> tags—unaltered. Strip oversized base64 tags or use proper XML/HTML escaping before sending rich text downstream.](https://kiweely.com/guides/workday-orchestrate-striphtmltags-2003-character-limit)

### More guides on Orchestrate

[All 86 guides](https://kiweely.com/guides#orchestrate)

-   [Why SendWorkdayRaasRequest returns 401 Unauthorized or empty data via the cloud proxy](https://kiweely.com/guides/workday-orchestrate-sendworkdayraasrequest-401-cloud-proxy)
-   [Reusing and versioning sub-orchestrations across Workday Extend and O4I apps](https://kiweely.com/guides/workday-orchestrate-reuse-sub-orchestrations-across-apps)
-   [Picking up SFTP files from subfolders and reading IDs from PDF filenames in Orchestrate](https://kiweely.com/guides/workday-orchestrate-sftp-subfolders-pdf-files)
-   [Sending email from Orchestrate: the Connect sendMessage API and email connectors](https://kiweely.com/guides/workday-orchestrate-send-email)
-   [How to keep large Workday Orchestrate loads inside the runtime limits: templates, checkpoints, batches and child runs](https://kiweely.com/guides/workday-orchestrate-runtime-limit-large-loads)
-   [How to rebuild an XSLT transformation in Workday Orchestrate](https://kiweely.com/guides/workday-orchestrate-replace-xslt)
-   [RaaS calls in Orchestrate: namespaces, unexpected character errors, 401s and empty reports](https://kiweely.com/guides/workday-orchestrate-raas-errors)
-   [How to process a CSV file in Orchestrate for Integrations, from Document Retrieval to the output file](https://kiweely.com/guides/workday-orchestrate-process-csv-file)

### From the blog on Orchestrate

[All posts](https://kiweely.com/blog)

-   [Why Workday Studio Remains Essential in an Orchestrate World](https://kiweely.com/blog/why-workday-studio-still-matters-with-orchestrate)
-   [Debugging Workday Extend apps and orchestrations in kiweely](https://kiweely.com/blog/debugging-workday-extend-apps-orchestrations-kiweely)
-   [Kiweely Roots vs Workday EIB, Studio, and Orchestrate](https://kiweely.com/blog/kiweely-roots-vs-workday-eib-studio-orchestrate)

## Let Workday check the work.

Kiweely writes WQL and builds orchestrations in your own tenant, and Workday, not Kiweely, says whether they passed.

[Start for free](https://kiweely.com/download) [See how it works](https://kiweely.com/vine/how-it-works)

## Get the next guide in your inbox.

One email a month with new guides and one Extend tip. Nothing else.
