BODtoJSON v2.6.0

BODtoJSON: Simplified Usage & Complete Use Case Guide

Transform complex Infor OAGIS XML Business Object Documents (BODs) into clean Python dictionaries, target API schemas, flat JSON, or streaming NDJSON in one line of code, using a zero-dependency stdlib parser for secure parsing. New in v2.6.0: map a BOD to your own nested JSON in one call with bod_to_json(xml, rules=TEMPLATE), including lines, conditions and merges. Since v2.5.0: if/else, case and concat rules, and JSON → BOD reverse conversion.

100% Python Standard Library Infor ION Scripting Ready Data Lakehouse & RAG Optimized Optional FastAPI Microservice One-Call Template Mapping If / Case / Concat Rules JSON → BOD Reverse

Infor ION in 3 Lines: Map a BOD to Your Own JSON

bod_to_json(input_var, rules=RULES) New in v2.6.0

Write the JSON you want as a template and put BOD field paths where values go. One call returns one object per noun. Order lines (repeat), nested coding lines, header fields inside lines, if/case conditions and merges all work without helper code, eval, or third-party packages.

from BODtoJSON import bod_to_json
RULES = {...}                                    # the JSON you want, with BOD paths as values
output_var = bod_to_json(input_var, rules=RULES)  # JSON array, one object per noun

Complete ION script (examples/ion_script.py, template in examples/ion_purchase_order_template.json):

from BODtoJSON import bod_to_json

RULES = {
    "externalSystemId": {"template": "{Sync_AccountingEntityID}_{PurchaseOrder_PurchaseOrderHeader_DisplayID}"},
    "isActive": True,
    "companyId": {"template": "company[{Sync_AccountingEntityID}]"},
    "amount": "PurchaseOrder_PurchaseOrderHeader_ExtendedAmount",
    "currencyCode": "PurchaseOrder_PurchaseOrderHeader_ExtendedAmount_@currencyID",
    "orderIdentifier": "PurchaseOrder_PurchaseOrderHeader_DisplayID",
    "registerDate": "PurchaseOrder_PurchaseOrderHeader_OrderDateTime",
    "supplier": "PurchaseOrder_PurchaseOrderHeader_SupplierParty_PartyIDs_ID",
    "externalSystemMetadata": [{}],
    "purchaseOrderLines": {
        "repeat": "PurchaseOrder_PurchaseOrderLine_*",
        "item": {
            "externalSystemId": {"template": "{Sync_AccountingEntityID}_{PurchaseOrder_PurchaseOrderHeader_DisplayID}_{PurchaseOrder_PurchaseOrderLine_*_LineNumber}"},
            "isActive": True,
            "amount": "PurchaseOrder_PurchaseOrderLine_*_ExtendedAmount",
            "lineNumber": "PurchaseOrder_PurchaseOrderLine_*_LineNumber",
            "quantity": "PurchaseOrder_PurchaseOrderLine_*_Quantity",
            "unit": "PurchaseOrder_PurchaseOrderLine_*_Quantity_@unitCode",
            "unitPrice": "PurchaseOrder_PurchaseOrderLine_*_UnitPrice_Amount",
            "codingLines": {"repeat": "CodingLine_*", "item": {}},
            "deliveryLines": [{"isActive": True, "externalSystemMetadata": [{}]}],
            "externalSystemMetadata": [{}],
        },
    },
    "purchaseOrderComments": [{}],
}

output_var = bod_to_json(input_var, rules=RULES)  # input_var / output_var are ION variables

Output (single=True, three-line order, abridged):

{
  "externalSystemId": "3555_PSU000051",
  "isActive": true,
  "companyId": "company[3555]",
  "amount": "1350.50",
  "currencyCode": "EUR",
  "orderIdentifier": "PSU000051",
  "registerDate": "2026-11-19T10:15:00Z",
  "supplier": "SUP0042",
  "externalSystemMetadata": [
    {}
  ],
  "purchaseOrderLines": [
    {
      "externalSystemId": "3555_PSU000051_10",
      "isActive": true,
      "amount": "500",
      "lineNumber": "10",
      "quantity": "5",
      "unit": "EA",
      "unitPrice": "100",
      "codingLines": [
        {},
        {}
      ],
      "deliveryLines": [
        {
          "isActive": true,
          "externalSystemMetadata": [
            {}
          ]
        }
      ],
      "externalSystemMetadata": [
        {}
      ]
    }
    // ... lines 20 and 30 ...
  ],
  "purchaseOrderComments": [
    {}
  ]
}
# Conditions and merges go straight into the template (no helper code):
"status": {"case": [{"when": {"eq": ["PurchaseOrder_PurchaseOrderHeader_Status_Code", "Open"]}, "then": "O"},
                    {"when": {"in": ["PurchaseOrder_PurchaseOrderHeader_Status_Code", ["Closed", "Done"]]}, "then": "C"}],
           "default": "?"},
"band":   {"if": {"gt": ["PurchaseOrder_PurchaseOrderHeader_ExtendedAmount", 1000]}, "then": "high", "else": "low"},
"label":  {"concat": ["PO-", "PurchaseOrder_PurchaseOrderHeader_DisplayID"]},
"total":  {"number": "PurchaseOrder_PurchaseOrderHeader_ExtendedAmount"},
"lines":  {"repeat": "PurchaseOrder_PurchaseOrderLine_*",
           "where": {"gt": ["ExtendedAmount", 0]},          # optional filter; paths may be relative to the line
           "item": {"no": "LineNumber", "item": "Item_ID"}}

bod_to_data() returns Python objects. single=True returns the first noun. missing="" returns empty strings instead of null. rules can be a dict, JSON text, or a file path, and Mapper.from_file(path) compiles a template once. CLI: bodtojson to-json order.xml --rules template.json. Full syntax: Output Template Reference.

Which Method Should I Use?

Pick the function that matches your destination system. All functions automatically strip XML namespaces, handle UTF-8 BOM characters, and remove the administrative OAGIS Verb (Sync, Process, Show, etc.).

Your Use Case Function to Call Return Type Best For
Map a BOD to your own nested JSON (lines, conditions, merges) bod_to_json(xml, rules=TEMPLATE) str (JSON) / bod_to_data: list[dict] Infor ION Scripting, REST payloads: the recommended starting point
Map BOD directly to a target REST API schema project(xml, verb, schema) list[dict] Infor ION Scripting, third-party SaaS connectors
Work with Python dicts & header metadata to_records(xml, verb, include_header=True) list[dict] Custom business rules, conditional logic in Python
Stream records to Snowflake, Databricks, or Vector DB to_ndjson(xml, verb) str (lines) Data Lakehouses, Kafka/Event Hubs, RAG pipelines
Get a single flat JSON string to_json(xml, verb) str (JSON) Document stores, webhook payloads, logging
Apply if/else, case, or merge rules before the JSON is produced to_records(xml, verb, rules=RULES) list[dict] Code mapping, derived fields, concatenated IDs (also on to_json, to_ndjson, project)
Build a BOD from JSON (reverse) json_to_bod(data, verb, noun) str (XML) Publishing to Infor ION from REST/JSON sources, round trips
Expose conversion as an HTTP microservice uvicorn BODtoJSON.api:app HTTP Response Containerized integration hubs, API gateways

Installation

Core Library vs. Full API Server Secure Parsing (stdlib)
# 1. Core library only (Ideal for Infor ION Scripting, AWS Lambda, ETL workers)
pip install BODtoJSON==2.6.0

# 2. Core library + FastAPI & Uvicorn REST server
pip install "BODtoJSON[api]==2.6.0"

# Also installs the `bodtojson` command (same as `python -m BODtoJSON`)

How XML Keys Are Flattened

Every nested XML tag is joined with an underscore (_) starting from the Noun root inside DataArea:

OAGIS XML Pattern Flattened Key Example Value
Simple element: <DisplayID>PSU000049</DisplayID> PurchaseOrder_PurchaseOrderHeader_DisplayID "PSU000049"
Element with attributes: <ID accountingEntity="3555">PSU000049</ID> ..._DocumentID_ID_#text
..._DocumentID_ID_@accountingEntity
"PSU000049"
"3555"
Repeating sibling tags: multiple <PurchaseOrderLine> ..._PurchaseOrderLine_0_LineNumber
..._PurchaseOrderLine_1_LineNumber
"10"
"20"
Header context (include_header=True) Sync_AccountingEntityID
ApplicationArea_Sender_LogicalID
"3555"
"lid://infor.ln..."

Every Use Case: Copy-Paste Ready

Use Case 1: Infor ION Scripting (Map BOD to Target API Schema) Recommended for ION

Eliminate manual ElementTree namespace parsing, json.loads() loops, and repetitive .get() boilerplate. Define a declarative dictionary and let project() extract header fields (Sync_AccountingEntityID), interpolate strings, map keys, and coerce booleans in one call.

import json
from BODtoJSON import project

# Declarative target schema:
# - "{Key}" interpolates any Noun or Header field (missing keys safely become "")
# - Exact key strings pull values directly
# - Callables (lambda) compute custom expressions
# - Constants (True, "DIMENSION1") pass straight through
SCHEMA = {
    "externalSystemId": "company[{Sync_AccountingEntityID}];DIMENSION1;{ChartOfAccounts_BaseChartOfAccounts_GLNominalAccount}",
    "companyId": "company[{Sync_AccountingEntityID}]",
    "dimensionName": "DIMENSION1",
    "isActive": True,
    "usableInPurchase": lambda r: r.get("ChartOfAccounts_Status_Code") == "Open"
}

# input_var is provided automatically by Infor ION Scripting
items = project(input_var, verb="Sync", schema=SCHEMA, include_header=True)
output_var = json.dumps(items)
Use Case 2: Native Python Dictionary List (Custom Business Logic) No JSON Round-Trip

When you need full Python control (filtering, enrichment, database inserts) without parsing JSON strings back and forth, use to_records(). It raises a standard ValueError on invalid XML.

from BODtoJSON import to_records

records = to_records(xml_payload, verb="Sync", include_header=True)

for rec in records:
    entity = rec.get("Sync_AccountingEntityID")
    po_id = rec.get("PurchaseOrder_PurchaseOrderHeader_DisplayID")
    amount = float(rec.get("PurchaseOrder_PurchaseOrderHeader_ExtendedAmount_#text", 0))
    print(f"Entity {entity} | PO {po_id} | Amount: {amount}")
Use Case 3: Data Lakehouse & Vector DB Streaming (NDJSON) High-Throughput ETL

Generates compact, zero-whitespace, newline-delimited JSON (\n terminated). Ideal for Snowflake Snowpipe, Databricks Auto Loader, AWS S3/Glue, and RAG embedding pipelines.

from BODtoJSON import to_ndjson

# Returns one compact JSON object per line, terminated with \n
ndjson_stream = to_ndjson(xml_payload, verb="Sync")

# Write directly to S3 / Data Lake staging file
with open("purchase_orders.ndjson", "w", encoding="utf-8") as f:
    f.write(ndjson_stream)
Use Case 4: Standard Flattened JSON String Document Stores

Converts the primary Noun inside DataArea into a single flat JSON string for NoSQL document databases, message queues, or webhook calls.

from BODtoJSON import to_json

flat_json_str = to_json(xml_payload, verb="Sync")
print(flat_json_str)
Use Case 5: Multi-Record Batch BODs Automatic Unpacking

When ERP LN publishes a batch BOD containing multiple sibling Nouns inside DataArea (e.g., 50 <PurchaseOrder> blocks in one SyncPurchaseOrder message), to_ndjson(), to_records(), and project() automatically unpack every Noun into its own record.

from BODtoJSON import to_records, to_ndjson

# Batch XML with 25 <ItemMaster> elements under <DataArea>
items = to_records(batch_item_xml, verb="Sync")
print(f"Unpacked {len(items)} individual records")

# Or emit 25 compact NDJSON lines in one call
lines = to_ndjson(batch_item_xml, verb="Sync")
Use Case 6: Custom Delimiter or Non-Standard Root Node Advanced Configuration

Instantiate BODConverter directly if you want dot-notation keys (PurchaseOrder.Header.ID) instead of underscores, or need to target a custom container node.

from BODtoJSON import BODConverter

# Use '.' instead of '_' for flattened keys
dot_converter = BODConverter(pnode="DataArea", separator=".")
records = dot_converter.to_records(xml_payload, verb="Process")

print(records[0]["PurchaseOrder.PurchaseOrderHeader.DisplayID"])
Use Case 7: REST Microservice Tier (FastAPI) Optional [api] Extra

Run BODtoJSON as a standalone HTTP service for non-Python applications or integration platforms.

# Start the server locally or inside Docker
uvicorn BODtoJSON.api:app --host 0.0.0.0 --port 8000

# Available Endpoints:
# POST /convert/ndjson?verb=Sync   (Body: raw text/plain XML -> application/x-ndjson)
# POST /convert/json?verb=Sync     (Body: raw text/plain XML -> application/json)
# POST /project                    (Body: {"xml": "...", "verb": "Sync", "schema_map": {...}, "rules": {...}?})
# POST /map                        (Body: {"xml": "...", "rules": {...template...}, "single": false})
# POST /transform                  (Body: {"xml": "...", "verb": "Sync", "rules": {...}, "include_header": false})
# POST /convert/bod                (Body: {"data": [...records...], "verb": "Sync", "noun": "PurchaseOrder"?,
#                                          "rules": {...}?, "action_code": "Replace"?} -> application/xml)
# GET  /health                     (Service health check)
Use Case 8: Legacy Code Compatibility Deprecated in v3.0.0

Existing scripts calling convert(xml, verb) continue to work without breaking changes, routing internally to to_json() while logging a non-blocking DeprecationWarning.

from BODtoJSON import convert

# Works seamlessly, emits DeprecationWarning (scheduled for removal in v3.0.0)
result = convert(xml_payload, verb="Sync")
Use Case 9: Transformation Rules (if/else, case, concat before JSON) New in v2.5.0

Derive or rewrite fields from BOD elements and attributes before the JSON is produced, using a declarative rules object (a dict, or JSON text from a file or an ION variable). Pass it as rules= to to_json, to_ndjson, to_records or project. "$Path" reads a flattened key and any other string is a literal. Rules are interpreted and never eval-ed, so they are safe in Infor ION.

import json
from BODtoJSON import to_json, to_records

RULES = {
    "mode": "merge",                 # keep all flattened fields; "only" = rule outputs only
    "drop": ["ApplicationArea_*"],   # optional glob patterns removed afterwards
    "rules": {
        # MERGE: literal prefix + element value
        "orderRef": {"concat": ["PO-", "$PurchaseOrder_PurchaseOrderHeader_DocumentID_ID"]},

        # MERGE: two elements with a separator (empty parts are skipped)
        "contactName": {"concat": ["$PurchaseOrder_PurchaseOrderHeader_Contact_FirstName",
                                   "$PurchaseOrder_PurchaseOrderHeader_Contact_LastName"],
                        "sep": " "},

        # TEMPLATE: placeholders are flattened keys (header keys need include_header=True)
        "company": {"template": "company[{Sync_AccountingEntityID}]"},

        # CASE / SWITCH on an attribute value
        "currencyName": {"case": "$PurchaseOrder_PurchaseOrderHeader_ExtendedAmount_@currencyID",
                         "when": {"EUR": "Euro", "USD": "US Dollar"},
                         "default": "Other"},

        # IF / ELSE-IF / ELSE based on another element
        "amountBand": {
            "if": [
                {"when": {"path": "PurchaseOrder_PurchaseOrderHeader_ExtendedAmount", "op": "ge", "value": 10000},
                 "then": "high"},
                {"when": {"path": "PurchaseOrder_PurchaseOrderHeader_ExtendedAmount", "op": "ge", "value": 1000},
                 "then": "medium"},
            ],
            "else": "low",
        },

        # Simple IF with combined conditions
        "needsApproval": {
            "if": {"all": [
                {"path": "PurchaseOrder_PurchaseOrderHeader_ExtendedAmount", "op": "gt", "value": 2000},
                {"path": "Sync_AccountingEntityID", "op": "in", "value": ["3555", "3556"]},
            ]},
            "then": True,
            "else": False,
        },

        # PER LINE: '*' binds to each repeated PurchaseOrderLine
        "PurchaseOrder_PurchaseOrderLine_*_lineKey": {
            "concat": ["$PurchaseOrder_PurchaseOrderHeader_DisplayID",
                       "$PurchaseOrder_PurchaseOrderLine_*_LineNumber"],
            "sep": "-",
        },
    },
}

records = to_records(xml_payload, verb="Sync", include_header=True, rules=RULES)
print(records[0]["orderRef"], records[0]["currencyName"], records[0]["amountBand"])
# -> PO-PSU000049 Euro medium

# Same rules work on to_json / to_ndjson / project, and as JSON text from a file:
flat = json.loads(to_json(xml_payload, verb="Sync", rules=open("rules.json").read()))
Use Case 10: Reverse Conversion (JSON → BOD) New in v2.5.0

json_to_bod() rebuilds the BOD envelope (root <Verb><Noun>, Infor OAGIS namespace, ApplicationArea, DataArea/<Verb>, one noun per record). Input can be flattened records, NDJSON, or nested JSON. The key conventions are the same as the forward converter (_@attr, _#text, _Line_0_), so to_records(include_header=True) → json_to_bod → to_records round-trips. Reverse rules map foreign JSON onto BOD paths.

from BODtoJSON import json_to_bod, to_records

# 1) Round trip: flattened records (with header) back to a BOD
records = to_records(xml_payload, verb="Sync", include_header=True)
xml_out = json_to_bod(records, verb="Sync", version_id="2.14.x")

# 2) Nested JSON, keys relative to the noun
#    "@name" = attribute, "#text" = element text, JSON arrays = repeated elements
xml_out = json_to_bod(
    {
        "PurchaseOrderHeader": {
            "DocumentID": {"ID": {"@variationID": "1", "#text": "PO-1001"}},
            "ExtendedAmount": {"@currencyID": "EUR", "#text": 2500},
        },
        "PurchaseOrderLine": [{"LineNumber": 10}, {"LineNumber": 20}],
    },
    verb="Sync",
    noun="PurchaseOrder",
    action_code="Replace",                                   # DataArea/Sync/ActionCriteria
    application_area={"Sender_LogicalID": "lid://infor.ln.ln01/3555"},
)

# 3) Foreign JSON + reverse rules (targets are BOD paths; default mode "only")
REVERSE = {"rules": {
    "PurchaseOrder_PurchaseOrderHeader_DocumentID_ID": {"template": "PO-{order_id}"},
    "PurchaseOrder_PurchaseOrderHeader_Status_Code": {
        "case": "$status", "when": {"O": "Open", "C": "Closed"}, "default": "Unknown"},
    "PurchaseOrder_PurchaseOrderHeader_CustomerParty_Name": {
        "concat": ["$customer_first_name", "$customer_last_name"], "sep": " "},
    "PurchaseOrder_PurchaseOrderLine_*_Item_ID": "$lines_*_sku",
    "PurchaseOrder_PurchaseOrderLine_*_Quantity_#text": "$lines_*_qty",
    "PurchaseOrder_PurchaseOrderLine_*_Quantity_@unitCode": {"upper": "$lines_*_uom"},
}}
order = {"order_id": 1001, "status": "O",
         "customer": {"first_name": "Ada", "last_name": "Lovelace"},
         "lines": [{"sku": "SKU-1", "qty": 5, "uom": "ea"}, {"sku": "SKU-2", "qty": 3, "uom": "kg"}]}
xml_out = json_to_bod(order, verb="Sync", noun="PurchaseOrder", rules=REVERSE)

Output of example 3:

<?xml version="1.0" encoding="UTF-8"?>
<SyncPurchaseOrder xmlns="http://schema.infor.com/InforOAGIS/2" releaseID="9.2">
  <ApplicationArea>
    <CreationDateTime>2026-11-20T06:30:00Z</CreationDateTime>
  </ApplicationArea>
  <DataArea>
    <Sync/>
    <PurchaseOrder>
      <PurchaseOrderHeader>
        <DocumentID>
          <ID>PO-1001</ID>
        </DocumentID>
        <Status>
          <Code>Open</Code>
        </Status>
        <CustomerParty>
          <Name>Ada Lovelace</Name>
        </CustomerParty>
      </PurchaseOrderHeader>
      <PurchaseOrderLine>
        <Item>
          <ID>SKU-1</ID>
        </Item>
        <Quantity unitCode="EA">5</Quantity>
      </PurchaseOrderLine>
      <PurchaseOrderLine>
        <Item>
          <ID>SKU-2</ID>
        </Item>
        <Quantity unitCode="KG">3</Quantity>
      </PurchaseOrderLine>
    </PurchaseOrder>
  </DataArea>
</SyncPurchaseOrder>

Fidelity notes: namespace prefixes, comments, original root attributes (such as xsi:schemaLocation), tail text, and the interleaving of different sibling names are not preserved. Siblings are grouped by element name. Element names that contain the separator round-trip only from nested input or with a different separator. Values are written as text (true → "true").

Use Case 11: Command Line (bodtojson) New in v2.5.0

A stdlib argparse CLI is installed with the core package. Exit code 0 means success and 1 means a conversion or rules error (message on stderr).

# BOD -> JSON with rules (json | ndjson | records)
bodtojson to-json order.xml --verb Sync --rules rules.json --format records --include-header --indent 2

# BOD -> NDJSON file
bodtojson to-json order.xml --format ndjson -o order.ndjson

# JSON / NDJSON -> BOD
bodtojson to-bod order.json --verb Sync --noun PurchaseOrder --rules reverse_rules.json --action-code Replace -o order.xml

# stdin / stdout, without the console script
python -m BODtoJSON to-bod - < records.json > order.xml

# Other to-bod options: --root, --namespace "" (omit), --release-id, --version-id,
#                       --no-application-area, --separator, --compact

Output Template Reference (bod_to_json)

Used by bod_to_json, bod_to_data, Mapper, POST /map and bodtojson to-json --rules. In output fields a plain string is a path. In operator arguments and results (then/else/default, case values, concat/coalesce items), a plain string is a path when the field exists or the string looks like a path (contains _ @ # *); otherwise it is text, so "then": "high" works. 2.5 flat rules ("$Path", mode/drop) are detected automatically and keep working.

In the template Result
"PurchaseOrder_..._DisplayID" Field value. _#text is tried automatically, and a leading $ or {…} is optional. Missing gives null (or missing=).
"{A}_{B}" / {"template": "company[{A}]"} Placeholders filled from fields (missing gives ""). {"template": "TEXT"} is constant text.
true 12 null {} [{}] Copied as is.
{...} / [...] Nested output shape.
{"literal": x} x unchanged.
{"path": "P", "default": d} Field with a default.
{"repeat": "PurchaseOrder_PurchaseOrderLine_*", "item": {...}, "where": cond} One item per repeated element (single unindexed element gives one item; none gives []). Inside item, * is the current row and paths may be relative ("LineNumber"). A nested "CodingLine_*" is relative to the row. Header fields work everywhere.
{"if": cond, "then": x, "else": y} If/else. A list of {"when", "then"} gives else-if.
{"case": [{"when": cond, "then": x}], "default": y} First matching branch.
{"case": "Path", "when": {"A": x}, "default": y} Map a field value.
{"concat": ["PO-", "Path"], "sep": ""} {"coalesce": ["A", "B"]} Merge / first non-empty.
upper lower trim number replace substr Helpers, e.g. {"number": "Path", "default": 0}.
{"eq": ["Path", "value"]} or {"path": "Path", "op": "eq", "value": "value"} Conditions: eq ne gt ge lt le in not_in contains not_contains starts_with ends_with exists missing empty not_empty, plus all / any / not. The value is a literal; use "$Other_Path" to compare two fields.

Bad templates raise BODTransformError naming the location, for example Rule at '$.purchaseOrderLines.repeat': repeat pattern must end with '_*'.

Transformation Rules Reference

A rules config is either a plain object of output_field: expression, or {"mode": "merge", "drop": ["glob*"], "rules": {...}}. mode "merge" (default for BOD → JSON) keeps every flattened field and adds or overrides the rule outputs. "only" (default for json_to_bod) emits only the rule outputs. drop removes keys that match the glob patterns after the rules run (rule targets are kept). Rules run in order, so a later rule can use an earlier rule's output.

Value expressions

Expression Meaning
"$Path" Value of a flattened key. If it is missing, Path_#text is tried, so $..._DocumentID_ID works on elements that have attributes. "$$x" is the literal "$x".
"text", 42, true, null Literal value.
{"path": "P", "default": "x"} Lookup with a default when the key is missing or null.
{"literal": [...]} Any JSON literal, including lists and objects.
{"concat": ["$A", " ", "$B"], "sep": "", "skip_empty": true} Merge fields and strings. Empty parts are skipped by default.
{"template": "PO-{A}/{B}"} String template. Placeholders are paths and missing values become "". Write {{ / }} for literal braces.
{"if": cond, "then": e, "else": e} If/else.
{"if": [{"when": cond, "then": e}, ...], "else": e} Else-if chain. The first match wins.
{"case": e, "when": {"A": e}, "default": e, "ignore_case": false} Case/switch.
{"case": e, "when": [{"match": ["A","B"], "then": e}]} Several values mapped to one result.
{"coalesce": [e, ...]} First non-empty value.
{"upper": e} {"lower": e} {"trim": e} Text helpers.
{"replace": e, "old": "a", "new": "b"} Replace text.
{"substr": e, "start": 0, "end": 3} Python-style slice.
{"number": e, "default": 0} Convert to int/float.

Conditions

Condition Meaning
{"path": "P", "op": "eq", "value": v} Compare a field. value is an expression, so "$Other" compares two fields.
{"expr": e, "op": ..., "value": v} Compare any expression, for example a concat.
op eq ne gt ge lt le (or == != > >= < <=), in not_in (list value), contains not_contains starts_with ends_with, exists missing empty not_empty. "ignore_case": true is optional.
{"all": [...]} {"any": [...]} {"not": c} Combine conditions (also and / or).
"$P" True when the field is not empty.

Comparisons are numeric when both sides are numbers ("2500" > 1000) and text otherwise. Without op, a condition with value means eq and one without means not_empty.

Repeated elements: a * segment binds to the index of repeated siblings. PurchaseOrder_PurchaseOrderLine_*_Quantity matches ..._PurchaseOrderLine_0_Quantity, ..._1_Quantity, and a single unindexed line. When the target contains *, the rule runs once per index.

Safety: rules are validated when compiled (unknown keys, bad operators, nesting limit 64) and raise BODTransformError. Evaluation uses no eval/exec, attribute access, imports, or regular expressions.

Complete API Reference

Signature Parameters Returns
bod_to_json(bod_xml, rules, verb=None, *, single=False, include_header=True, missing=None, kind="auto", separator="_", indent=None) rules: Output template (or 2.5 flat rules) as a dict, JSON text, or file path.
verb: Detected when None.
single: Return the first noun's object instead of a list.
missing: Value for absent fields (default null).
str (JSON)
bod_to_data(...) / Mapper(rules).to_data(xml) / Mapper.from_file(path) Same options. Returns Python objects. Mapper.apply(record) maps one flattened record. list / dict
project(bod_xml, verb, schema, include_header=True, coerce_booleans=True, rules=None) bod_xml (str): Raw OAGIS XML.
verb (str): OAGIS Verb to strip (e.g. "Sync").
schema (dict): Target field mapping rules.
include_header (bool): Include ApplicationArea & Verb fields.
coerce_booleans (bool): Convert "true"/"false" strings to bool.
rules (dict | str | TransformRules): Optional transformation rules applied before projection.
List[Dict[str, Any]]
to_records(bod_xml, verb, include_header=False, rules=None) bod_xml (str): Raw OAGIS XML.
verb (str): OAGIS Verb to strip.
include_header (bool): Merge header metadata into each record.
rules: Optional transformation rules.
List[Dict[str, Any]]
to_ndjson(bod_xml, verb, raise_on_error=False, rules=None, include_header=False) bod_xml (str): Raw OAGIS XML.
verb (str): OAGIS Verb to strip.
rules: Optional transformation rules.
include_header (bool): Add header fields to each line.
str (Newline-delimited compact JSON)
to_json(bod_xml, verb, raise_on_error=False, rules=None) bod_xml (str): Raw OAGIS XML.
verb (str): OAGIS Verb to strip.
rules: Optional transformation rules (first noun, no header).
str (Flat JSON string)
BODConverter(pnode='DataArea', separator='_') pnode (str): Container tag holding Verb & Noun.
separator (str): Delimiter between nested tag names.
BODConverter instance
json_to_bod(data, verb="Sync", noun=None, *, rules=None, separator="_", namespace=INFOR_OAGIS_NS, root=None, release_id="9.2", version_id=None, application_area=None, include_application_area=True, action_code=None, flat=None, pretty=True, xml_declaration=True) data: JSON/NDJSON text, bytes, a dict, or a list of dicts (one noun per record). Flattened, nested, or mixed.
noun: Place keys relative to this noun.
rules: Reverse rules (default mode "only").
action_code: Adds ActionCriteria/ActionExpression/@actionCode.
include_application_area: Generate ApplicationArea/CreationDateTime when none is given.
str (BOD XML)
BODConverter(...).from_json(data, verb, noun, **kwargs) Same as json_to_bod, using the converter's separator, max_size, and max_depth. str (BOD XML)
apply_rules(record_or_records, rules) / TransformRules(config).apply(record) Apply rules to flattened dicts directly. compile_rules() validates once for reuse. dict / list[dict]
BODParseError / BODStructureError / BODTransformError Malformed input / structure that cannot be converted / invalid rules. Exceptions

Interactive Output Previewer

Test how your OAGIS XML flattens directly in the browser before deploying to Infor ION.