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.5.0: if/else, case and concat transformation rules, and JSON → BOD reverse conversion.
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 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
# 1. Core library only (Ideal for Infor ION Scripting, AWS Lambda, ETL workers) pip install BODtoJSON==2.5.0 # 2. Core library + FastAPI & Uvicorn REST server pip install "BODtoJSON[api]==2.5.0" # 2.5.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_AccountingEntityIDApplicationArea_Sender_LogicalID |
"3555""lid://infor.ln..." |
Every Use Case: Copy-Paste Ready
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)
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}")
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)
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)
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")
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"])
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 /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)
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")
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()))
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").
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
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 |
|---|---|---|
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.