An EDI parser you can debug at two in the morning
The format is simple enough that everybody writes the first parser with a split and a regular expression. The second one gets written after a file fails in production and nobody can say which segment was the problem.
X12 looks trivial. Segments separated by one character, elements by another, components by a third. A split and a loop and you are reading claims in twenty minutes.
Then a remittance arrives that posts twelve cents to the wrong account, and the question is which segment in a 40,000-line file caused it. The twenty-minute parser has no answer, because it threw away everything except the values it wanted.
The difference between the first parser and the one you keep is almost entirely about what it remembers.
Keep the position of everything
Every value a parser extracts should know where it came from: the segment type, which occurrence of that segment it was, its position in the file, and the element and component index within it.
That is the single most valuable design decision in the whole exercise, and it pays off in four places:
- An acknowledgment that reports an error by element position can be resolved back to a field.
- A posting error can be traced to the exact segment that produced it.
- A validation message can quote the offending value and its address.
- A support conversation with a trading partner can cite segment and element rather than describing the problem in prose.
Concretely: parse to a list of segments, each with its index in the file, its tag, and its elements as arrays of components. Resist the urge to parse straight into your domain objects. The intermediate representation is what you have left when something goes wrong, and it is also what makes the parser testable without a database.
Read the delimiters, do not assume them
The delimiters are declared in the interchange header itself. The segment terminator, the element separator, the component separator and the repetition separator are all properties of the file in front of you, not constants.
Hard-coding them works for years with one trading partner and breaks the first day you add another. Worse, it breaks in a way that produces a parse with no error — one enormous segment, no claims found, an empty batch, and nothing in the log that says why.
The other half of the same discipline: do not treat whitespace as meaningless. Some segments are fixed-width and space-padded, and trimming an identifier changes it. Trim at the point of use, with the rules for that field, rather than globally at parse time.
Loops are a stack, not a nesting of objects
The thing that makes X12 awkward is that it is a flat list of segments with a hierarchy implied by position and by loop identifiers. There are no closing brackets. A claim loop ends because another one begins, or because a segment appears that cannot belong to it.
Two approaches work and one does not.
A stack machine reads segments in order and maintains the current loop context: this segment starts a claim, so close the previous claim; this one is a service line, so attach it to the current claim. It handles unexpected segments gracefully — an unknown tag inside a claim is recorded, not fatal — and it is straightforward to test.
A table-driven reader encodes the implementation guide's structure as data and walks it. More work, stricter, better at reporting a segment that appeared where the guide does not allow it. Worth it if you are validating as well as reading.
What does not work is matching segments by pattern across the whole file and assuming order. It produces a parser that is right on the files you have and silently wrong when a payer sends the segments in a legal order you did not anticipate.
What bites once it is live
One file, many transaction sets. A single interchange can contain several 835s for different payers, or an 837 batch for several payers. A parser that returns "the remittance" from a file will drop the second one, and the money in it.
Line endings. Some senders terminate segments and also add a newline. Some use the newline as the terminator. Some wrap to fixed-width lines mid-segment. A parser that reads line by line is making an assumption the format does not support — read by delimiter, treat the newline as insignificant whitespace, and keep the original bytes.
Encoding. The standard's basic character set is restrictive, but senders include characters outside it, and a patient's name with an accent in it should not crash a parser or arrive mangled in a database with a different encoding than the file had.
A repeated segment that you expected once. Guides say a segment may appear once, and files contain it twice. Decide the policy — first wins, last wins, or raise — write it down, and apply it consistently rather than letting it be whatever your dictionary assignment happened to do.
The file that is almost right. Truncated transfers, a file written while still uploading, an envelope with no closing segment. Validate the envelope before parsing the contents: the counts and the paired control numbers tell you whether you have the whole file, and a partial file posted as if complete is worse than a rejected one.
Idempotent reprocessing. You will need to re-run a file after fixing a posting bug. That is only safe if processing is keyed on something stable from the file itself, so a second run updates rather than duplicates. Design for it on day one; retrofitting it means reconciling what the first run did.
How to test it
- A file with non-standard delimiters parses identically to the same file with standard ones.
- A file containing three transaction sets returns three.
- The envelope counts and paired control numbers are validated before any content is read, and a truncated file is rejected with a message naming what was missing.
- A segment appearing twice where the guide allows one behaves according to the written policy, and a test names the policy.
- A round trip: parse a file, write it back, and compare byte for byte. Anything the parser silently normalises shows up here, which is exactly where you want to find out about it.
- An unknown segment tag inside a known loop is retained and does not stop the parse.
- The same file processed twice produces one set of postings.
- A real published sample file from each transaction type parses clean. Keep them in the fixture set with their provenance noted.
What we do
We parse to a positional intermediate representation before anything touches the domain model, read the delimiters from the envelope, validate the envelope before trusting the contents, and keep the original file so that a bad posting can be traced to a segment and the file can be reprocessed once the bug is fixed.
Building something that has to talk to a payer?
If any of the above is a problem you currently have, describe it and we will tell you what we would do about it.