Spring › Feature

Parsing legacy Dangi dates and court names in public data

How I fixed Dangi calendar conversion, court name normalization, and merged case-number false positives when ingesting Korean public court records.

Parsing legacy Dangi dates and court names in public data

Public judicial APIs rarely match their own documentation. This post walks through three real parsing failures I hit while ingesting Korean court precedents—legacy Dangi calendar years, inconsistent court abbreviations, and merged case-number false positives—and how I fixed them with domain validation, boundary regexes, and immutable raw re-parsing.

Tested with Spring Boot 3.4, Kotlin 2.1, and Java 21.

The problem: dirty data in public judicial APIs

If you trust an external public API spec at face value, production data will break your parser. Open APIs that serve decades of judicial records—such as Korea’s National Law Information Center precedent API—digitize paper archives written across different eras. Schema consistency breaks down fast.

While building a backend ingestion pipeline for hundreds of thousands of court precedents, three classes of dirty data repeatedly halted my parsing and reconciliation batch jobs.

flowchart TD
    Raw["Public Precedent API Response (JSON)"] --> Check{"Parse and Reconcile"}
    Check -->|"Issue 1"| Issue1["Dangi date: 42880215<br/>(Dangi 4288 = 1955 CE)"]
    Check -->|"Issue 2"| Issue2["Court mismatch<br/>List: Full name vs Body: Abbr + Panel"]
    Check -->|"Issue 3"| Issue3["Merged case range<br/>4285-MinSang-169 vs 1691"]
    Issue1 --> Fail1["Future year stored or parse failure"]
    Issue2 --> Fail2["Same case rejected as mismatch"]
    Issue3 --> Fail3["Naive contains() collides across cases"]
  1. Legacy Dangi calendar dates: Supreme Court rulings issued before 1962 sometimes return ruling dates like 42880215 (Dangi year 4288, February 15—which is February 15, 1955 CE). Calling LocalDate.parse directly either stores a ruling from the year 4288 or trips date validation.
  2. Mixed court abbreviations and judicial panels: The listing endpoint returns official names (for example, Seoul High Court), while the judgment body and news excerpts mix short forms and panel suffixes (Seoul High Ct., Suwon Dist. Ct. Ansan Branch, Seoul High Ct. Criminal Div. 1). Reconciliation rejects matching records as listingMismatch.
  3. Partial-match false positives on merged case numbers: When a judgment body lists a consolidated range such as 4285-MinSang-169 to 177, a naive contains check against 4285-MinSang-169 also matches a completely different case like 4285-MinSang-1691.

Here is how I resolved each failure with explicit domain rules and safe regex boundaries.


Fix 1: Detecting and converting Dangi calendar dates

South Korea used the Dangi (Dangun era) calendar officially from 1948 until December 31, 1961. Under Act No. 775 (Act on the Era Name), the country switched to the Gregorian calendar on January 1, 1962. Older digitized precedents still carry Dangi timestamps in the raw source.

The Dangi calendar runs 2,333 years ahead of the Gregorian calendar. If a parsed year is 4000 or greater, subtracting 2333 converts it to the Gregorian year. One guardrail matters here: if the converted year exceeds 1961, the input isn’t a valid historical Dangi date—it’s a typo or corrupted field and must be rejected.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// src/main/kotlin/com/example/server/judgment/application/JudgmentParser.kt
package com.example.server.judgment.application

import org.springframework.stereotype.Component
import java.time.DateTimeException
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@Component
class JudgmentParser {

    companion object {
        const val VERSION = "law-prec-v4"
        private const val DANGI_MIN_YEAR = 4000
        private const val DANGI_OFFSET = 2333L
        /** Dangi was the official calendar through December 31, 1961. */
        private const val DANGI_LAST_YEAR = 1961
        /** Sentinel value for unknown ruling dates (avoids storing year 0001). */
        const val UNKNOWN_DATE = "00010101"
    }

    fun parseDate(value: String?): LocalDate? {
        if (value == null) return null
        val digits = value.replace(Regex("[. /\\-\\s]"), "")
        if (!digits.matches(Regex("\\d{8}"))) {
            throw JudgmentParseException("Unrecognized ruling date format.")
        }
        if (digits == UNKNOWN_DATE) return null

        val parsed = try {
            LocalDate.parse(digits, DateTimeFormatter.BASIC_ISO_DATE)
        } catch (e: DateTimeException) {
            throw JudgmentParseException("Ruling date is not a valid calendar date.")
        }

        // Standard Gregorian year: return as-is
        if (parsed.year < DANGI_MIN_YEAR) return parsed

        // Pre-1962 records may use Dangi era dates (e.g., 42880215 -> 1955-02-15)
        return parsed.minusYears(DANGI_OFFSET).takeIf { it.year <= DANGI_LAST_YEAR }
            ?: throw JudgmentParseException("Converted Dangi date exceeds 1961.")
    }
}
  • digits == UNKNOWN_DATE: Maps placeholder 00010101 values to null instead of polluting date range queries with year 1 AD.
  • parsed.year < 4000: Passes ordinary Gregorian dates through untouched.
  • parsed.minusYears(2333L): Converts 42880215 to 1955-02-15.
  • .takeIf { it.year <= 1961 }: Rejects impossible post-abolition values like 43000101 (which would convert to 1967) instead of silently accepting bad data.

Unit test console output verifying Dangi calendar to Gregorian date conversion Figure 1. Unit test run confirming Dangi 4288 converts to 1955-02-15 while post-1961 values fail validation.


Fix 2: Normalizing court abbreviations and judicial panels

In raw precedent headers and news articles, Korean court names appear in inconsistent formats:

Raw input patternNormalized official nameTransformation applied
Seoul High Ct. (abbr. gobeop)Seoul High Court (godeung-beobwon)Expand High Court suffix
Suwon Dist. Ct. Ansan Branch (abbr. jibeop)Suwon District Court Ansan BranchExpand District Court suffix and preserve branch
Seoul High Ct. Criminal Div. 1Seoul High CourtExpand suffix and strip panel designation

Leaving these variants unnormalized does more than break list-to-body reconciliation. It fragments downstream entities: the same judge ends up linked to both Seoul High Ct. and Seoul High Court as separate career records.

To expand abbreviations without corrupting unrelated substrings, I anchor the regex with lookbehind and lookahead assertions. In the Korean production parser, the preceding character class targets Hangul syllables ([\uAC00-\uD7A3]) so only place-name-prefixed suffixes expand, and the trailing boundary requires whitespace or end-of-string.

1
2
3
4
5
6
7
8
9
10
11
// src/main/kotlin/com/example/server/judgment/application/JudgmentParser.kt
companion object {
    // Production Korean rules match Hangul place-name prefixes via [\uAC00-\uD7A3]
    // and expand short forms ("gobeop" -> "godeung-beobwon", "jibeop" -> "jibang-beobwon").
    private val HIGH_COURT_ABBR = Regex("(?<=[A-Za-z\\uAC00-\\uD7A3])\\s*High Ct\\.(?=$|\\s)")
    private val DIST_COURT_ABBR = Regex("(?<=[A-Za-z\\uAC00-\\uD7A3])\\s*Dist\\. Ct\\.(?=$|\\s)")

    fun courtName(value: String): String = value
        .replace(HIGH_COURT_ABBR, " High Court")
        .replace(DIST_COURT_ABBR, " District Court")
}

When extracting court names from news snippets or judgment headers that include a judicial panel (Criminal Div. 1, Civil Div. 2), a second rule strips everything after Court or Branch and verifies that the extracted name actually appears in the compact document body:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/main/kotlin/com/example/server/discovery/application/DiscoveryRules.kt
fun court(value: String, compactBody: String): String? {
    val expanded = JudgmentParser.courtName(value).trim()
    // Capture up to "Court" or "Branch", trimming trailing panel names (e.g., "Criminal Div. 1")
    val name = Regex("^(.*?(?:Court(?:\\s+[A-Za-z]+\\s+Branch)?|Branch))")
        .find(expanded)
        ?.groupValues?.get(1)
        ?: return null

    val compactName = name.replace(Regex("\\s+"), "")
    val abbreviated = compactName
        .replace("HighCourt", "HighCt.")
        .replace("DistrictCourt", "Dist.Ct.")

    if (compactName !in compactBody && abbreviated !in compactBody) {
        return null
    }
    return name.take(100)
}

Standardized mapping table for court abbreviations and panel stripping Figure 2. Mapping rules that expand court abbreviations and isolate judicial panels from the base court name.

Applying JudgmentParser.courtName symmetrically during both ingestion (JudgmentParser) and reconciliation (JudgmentImportService) eliminated false listingMismatch holds caused by court name formatting.


Fix 3: Guarding merged case numbers with negative lookaround

The precedent list API exposes only the lead case number—for instance, 4285-MinSang-169 (where MinSang is the civil appeal code). In the full ruling text, however, consolidated cases appear as ranges or comma-separated lists like 4285-MinSang-169 to 177 or 2020-Do-1234, 1235 (consolidated).

My first attempt used a plain substring check: compact(parsed.caseNumber).contains(compact(raw.listCaseNumber)). That created a silent data-corruption hazard.

Why contains is dangerous here
If the list case number is 4285-MinSang-169, a body with case number 4285-MinSang-1691 still satisfies contains. The importer treats two unrelated rulings as a match and overwrites the wrong record.

The fix is a digit-boundary check using negative lookbehind (?<!\d) and negative lookahead (?!\d) around the escaped case number. The match succeeds only when no digit immediately precedes or follows the target case number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/main/kotlin/com/example/server/judgment/application/JudgmentImportService.kt
package com.example.server.judgment.application

class JudgmentImportService {

    private fun listingMismatch(raw: RawJudgment, parsed: ParsedJudgment): String? {
        fun compact(value: String?) = value?.replace(Regex("\\s+"), "")?.ifEmpty { null }

        val caseNumber = compact(raw.listCaseNumber)
        // Match merged ranges ("4285-MinSang-169 to 177") without matching "4285-MinSang-1691"
        val boundaryPattern = caseNumber?.let { Regex("(?<!\\d)${Regex.escape(it)}(?!\\d)") }
        if (boundaryPattern != null && !boundaryPattern.containsMatchIn(compact(parsed.caseNumber).orEmpty())) {
            return "List case number (${raw.listCaseNumber}) does not match body (${parsed.caseNumber})."
        }

        // Normalize abbreviations on both sides before comparing court names
        val court = compact(raw.listCourtName?.let(JudgmentParser::courtName))
        if (court != null && parsed.courtName != null && court != compact(parsed.courtName)) {
            return "List court (${raw.listCourtName}) does not match body (${parsed.courtName})."
        }

        return null
    }
}

Substring check vs. digit-boundary regex

List case numberBody case numberPlain contains(?<!\d)...(?!\d)Result
4285-MinSang-1694285-MinSang-169 to 177truetrueAccepted (merged range)
4285-MinSang-1694285-MinSang-1691true (false positive)falseRejected (distinct case)
2020-Do-12342020-Do-1234, 1235truetrueAccepted (comma-separated)

Console log showing boundary regex accepting merged case ranges and rejecting suffix collisions Figure 3. Verification log showing the digit-boundary pattern accepting merged ranges while blocking suffix collisions.

When not to over-normalize

Regex normalization has a clear limit: never guess when the source is genuinely ambiguous. If a date converts to 1967, or if a court string lacks a recognizable court/branch suffix, fail the record into a review queue rather than inventing a fallback value. Silent coercion is much harder to debug later than an explicit parse hold.


Re-parsing held records with zero external API calls

Fixing parser bugs doesn’t help the thousands of records already sitting in a held or broken state. Re-fetching them from the public API wastes daily rate-limit quotas and adds unnecessary network latency.

Because the ingestion pipeline stores every unmodified API payload in an immutable raw_judgments table (covered in my note on raw data immutability and re-parsing), I only had to bump JudgmentParser.VERSION from law-prec-v3 to law-prec-v4 and trigger an internal re-parse job.

sequenceDiagram
    autonumber
    actor Admin as "Admin / Batch Job"
    participant DB as "PostgreSQL (raw_judgments)"
    participant Parser as "JudgmentParser (v4)"
    participant Core as "judgments (Domain Table)"
    Admin->>DB: Select rows WHERE parser_version < 'law-prec-v4'
    DB-->>Parser: Return immutable raw JSON payloads
    Note over Parser: 1. Convert Dangi dates<br/>2. Expand court abbreviations<br/>3. Verify digit boundaries
    Parser->>Core: Upsert normalized domain entities
    Core-->>Admin: Re-parse complete (0 external API calls)

Running that local transaction cleared roughly 1,200 held records—covering both Dangi-dated rulings and abbreviated court names—without spending a single external API request.


Production checklist

Before deploying a public-data parser to production, verify these four guardrails:

  • Historical date bounds: Reject converted dates outside the era’s real validity window (e.g., <= 1961 for Dangi) and map sentinel dates like 00010101 to null.
  • Symmetric normalization: Run the exact same normalization function on both listing metadata and full-text extracts before comparing fields.
  • Explicit regex boundaries: Replace substring contains checks on numeric identifiers with (?<!\d)...(?!\d) and Regex.escape.
  • Versioned immutable raw storage: Persist raw responses alongside a parser_version column so rule fixes replay locally with zero API quota cost.

References

This post is licensed under CC BY 4.0 by the author.