<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexio on Medium]]></title>
        <description><![CDATA[Stories by Alexio on Medium]]></description>
        <link>https://medium.com/@alexorabo?source=rss-23deff06dd72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Alexio on Medium</title>
            <link>https://medium.com/@alexorabo?source=rss-23deff06dd72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:20:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexorabo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Efficiently Processing Large MRF Files with JSON Schema and Python and a little sprinkle of ChatGPT]]></title>
            <link>https://medium.com/@alexorabo/efficiently-processing-large-mrf-files-with-json-schema-and-python-and-a-little-sprinkle-of-chatgpt-ea28c45e1010?source=rss-23deff06dd72------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea28c45e1010</guid>
            <dc:creator><![CDATA[Alexio]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 23:15:03 GMT</pubDate>
            <atom:updated>2024-09-17T13:26:56.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Handling large JSON files is often a challenging task, especially when working with Machine-Readable Files (MRF) in healthcare, which can span gigabytes in size. These files, rich in nested data, are essential for various applications but present significant challenges in processing due to their size. In this article, I will share my approach to processing large MRF files using JSON schema validation, Azure Durable Functions, and Python, while acknowledging the role ChatGPT played in helping me figure out the initial boilerplate code.</p><h4>Background</h4><p>Machine-Readable Files (MRF) are a cornerstone in data exchange in the healthcare industry. These files, typically in JSON format, contain complex, nested information such as negotiated rates, provider references, and service details. Processing them efficiently requires a strategy that avoids loading the entire file into memory, as this can lead to memory exhaustion or performance degradation.</p><p>As a first step, I used FastAPI to facilitate the uploading of zipped MRF archives and unzipping them on the server. This allowed me to handle the files in a more efficient manner, avoiding issues related to direct uploads of massive JSON files that could take several minutes to process. Although this part is not covered in detail in this article, it played a crucial role in setting up an effective workflow for handling these large files.</p><p>Inspired by <a href="https://medium.com/@lakshmi_priya_ramisetty/handling-large-json-files-without-fully-loading-them-into-memory-ce3d020a3f82">Lakshmi Priya Ramisetty’s article</a>, I set out to develop my approach for parsing these files incrementally using Python.</p><h4>Defining the Problem</h4><p>The goal was to parse large MRF JSON files and extract specific information, such as provider references and in-network details, using a memory-efficient approach. The main challenges included:</p><ol><li><strong>Memory Management</strong>: Avoiding loading the entire JSON file into memory.</li><li><strong>Data Integrity</strong>: Ensuring all relevant fields are processed and extracted correctly.</li><li><strong>Performance</strong>: Efficiently reading and processing large files without significant delays.</li></ol><h4>Approach</h4><p><strong>Using JSON Schema</strong></p><p>The JSON schema, such as the one provided by <a href="https://github.com/CMSgov/price-transparency-guide/blob/master/schemas/in-network-rates/in-network-rates.json">CMS</a>, offers a structural blueprint to understand the required fields. However, the schema alone is not sufficient to capture the complexity of parsing logic. This is because each insurance provider may represent these complicated JSON map structures differently, leading to a variety of interpretations and formats that may not always neatly align with the schema. Thus, building a universal solution for MRF file parsing requires working with real-world examples, not just files that perfectly fit the schema.</p><p><strong>Incremental Parsing with Python</strong></p><p>To handle large files without loading them fully into memory, the ijson library was utilized. This library enables parsing JSON files in a streaming manner, yielding elements one at a time, which is ideal for large files.</p><h4>Detailed Code Implementation</h4><p>Here is the example implementation, which separates tasks for parsing provider_references and in_network data, and uses an efficient approach to save parsed data incrementally:</p><pre><br># mrfunroller/provider_references.py<br>import ijson<br><br>def parse_provider_references(json_file_path):<br>    provider_references = {}<br><br>    with open(json_file_path, &#39;r&#39;) as file:<br>        parser = ijson.parse(file)<br>        for prefix, event, value in parser:<br>            if prefix == &#39;provider_references.item&#39; and event == &#39;start_map&#39;:<br>                current_group_id = None<br>                current_providers = []<br>            elif prefix.endswith(&#39;provider_group_id&#39;) and event == &#39;number&#39;:<br>                current_group_id = value<br>            elif prefix.endswith(&#39;provider_groups.item&#39;) and event == &#39;start_map&#39;:<br>                current_provider = {&#39;npi&#39;: [], &#39;tin&#39;: {}}<br>            elif prefix.endswith(&#39;npi.item&#39;) and event == &#39;number&#39;:<br>                current_provider[&#39;npi&#39;].append(value)<br>            elif prefix.endswith(&#39;tin.type&#39;) and event == &#39;string&#39;:<br>                current_provider[&#39;tin&#39;][&#39;type&#39;] = value<br>            elif prefix.endswith(&#39;tin.value&#39;) and event == &#39;string&#39;:<br>                current_provider[&#39;tin&#39;][&#39;value&#39;] = value<br>            elif prefix.endswith(&#39;provider_groups.item&#39;) and event == &#39;end_map&#39;:<br>                current_providers.append(current_provider)<br>            elif prefix == &#39;provider_references.item&#39; and event == &#39;end_map&#39;:<br>                provider_references[current_group_id] = current_providers<br><br>    return provider_references</pre><p>The in_network map is parsed by the following methods:</p><pre># m/in_network.py<br><br>import ijson<br>from collections import defaultdict<br>import json<br>import os<br><br>def parse_in_network(json_file_path, output_file_path):<br>    pointer = None  # Keep track of the last processed tuple<br>    processed_count = 0<br>    accumulated_data = []  # To accumulate results in memory<br><br>    with open(json_file_path, &#39;r&#39;) as file:<br>        parser = ijson.parse(file)<br>        current_pointer = pointer<br><br>        grouped_entries = defaultdict(lambda: {<br>            &#39;billing_code_type&#39;: None,<br>            &#39;billing_code&#39;: None,<br>            &#39;provider_group_ids&#39;: []<br>        })<br><br>        for prefix, event, value in parser:<br>            # Skip to the pointer position if it exists<br>            if current_pointer and prefix &lt; current_pointer:<br>                continue<br><br>            if prefix == &#39;in_network.item&#39; and event == &#39;start_map&#39;:<br>                item = parse_single_in_network(parser)<br>                processed_item = process_in_network_item(item)<br><br>                if processed_item is not None:<br>                    billing_code_type, billing_code, name, description, provider_group_ids = processed_item<br>                    grouped_key = (name, description)<br>                    grouped_entries[grouped_key][&#39;billing_code_type&#39;] = billing_code_type<br>                    grouped_entries[grouped_key][&#39;billing_code&#39;] = billing_code<br>                    grouped_entries[grouped_key][&#39;provider_group_ids&#39;].extend(provider_group_ids)<br>                    processed_count += 1<br>                    provlist = sorted(list(set(provider_group_ids)), key=lambda x: float(x))<br><br>                    accumulated_data.append({<br>                        &#39;name&#39;: name,<br>                        &#39;description&#39;: description,<br>                        &#39;billing_code_type&#39;: billing_code_type,<br>                        &#39;billing_code&#39;: billing_code,<br>                        &#39;provider_group_ids&#39;: provlist<br>                    })<br>                current_pointer = prefix    <br><br>            # Save results to file when a batch of entries is accumulated<br>            if processed_count &gt;= 100:<br>                save_to_file(accumulated_data, output_file_path)<br>                accumulated_data.clear()<br>                processed_count = 0<br><br>    if accumulated_data:<br>        save_to_file(accumulated_data, output_file_path)<br><br>def parse_single_in_network(parser):<br>    current_entry = {<br>        &#39;negotiation_arrangement&#39;: None,<br>        &#39;billing_code_type&#39;: None,<br>        &#39;billing_code&#39;: None,<br>        &#39;name&#39;: None,<br>        &#39;description&#39;: None,<br>        &#39;provider_group_ids&#39;: set()<br>    }<br><br>    for prefix, event, value in parser:<br>        if prefix.endswith(&#39;negotiation_arrangement&#39;) and event == &#39;string&#39;:<br>            current_entry[&#39;negotiation_arrangement&#39;] = value<br>        elif prefix.endswith(&#39;billing_code_type&#39;) and event == &#39;string&#39;:<br>            current_entry[&#39;billing_code_type&#39;] = value<br>        elif prefix.endswith(&#39;billing_code&#39;) and event == &#39;string&#39;:<br>            current_entry[&#39;billing_code&#39;] = value<br>        elif prefix.endswith(&#39;name&#39;) and event == &#39;string&#39;:<br>            current_entry[&#39;name&#39;] = value<br>        elif prefix.endswith(&#39;description&#39;) and event == &#39;string&#39;:<br>            current_entry[&#39;description&#39;] = value<br>        elif prefix.endswith(&#39;negotiated_rates.item.provider_references.item&#39;) and event == &#39;number&#39;:<br>            group_ids = str(value) if isinstance(value, (int, float)) else value<br>            current_entry[&#39;provider_group_ids&#39;].add(group_ids)<br><br>        if prefix == &#39;in_network.item&#39; and event == &#39;end_map&#39;:<br>            break<br><br>    return current_entry<br><br>def process_in_network_item(entry):<br>    if all(entry.get(key) is not None for key in [&#39;billing_code_type&#39;, &#39;billing_code&#39;, &#39;name&#39;, &#39;description&#39;]):<br>        return (<br>            entry.get(&#39;billing_code_type&#39;),<br>            entry.get(&#39;billing_code&#39;),<br>            entry.get(&#39;name&#39;),<br>            entry.get(&#39;description&#39;),<br>            list(entry.get(&#39;provider_group_ids&#39;, []))<br>        )<br>    return None<br><br>def save_to_file(data, output_file_path):<br>    with open(output_file_path, &#39;a&#39;) as f:  # Append mode to add data incrementally<br>        for entry in data:<br>            json.dump(entry, f)<br>            f.write(&#39;\n&#39;)<br><br>def read_output_file_line_by_line(output_file_path):<br>    try:<br>        with open(output_file_path, &#39;r&#39;) as file:<br>            for line in file:<br>                if line.strip():<br>                    data = json.loads(line)<br>                    print(data)<br>    except FileNotFoundError:<br>        print(f&quot;The file {output_file_path} does not exist.&quot;)<br>    except Exception as e:<br>        print(f&quot;An error occurred while reading the file: {e}&quot;)<br>    finally:<br>        if os.path.exists(output_file_path):<br>            os.remove(output_file_path)<br>            print(f&quot;The file {output_file_path} has been deleted.&quot;)<br>        else:<br>            print(f&quot;The file {output_file_path} was not found for deletion.&quot;)</pre><p>Due to the complexity and size of the JSON maps within the in_network map of the MRF files, it was necessary to implement a strategy to periodically cache the parsed data to prevent memory overflow issues with the ijson library. Given that each in_network entry can contain multiple nested objects with extensive details, the JSON parser may run out of memory when processing these large datasets. To mitigate this, we designed the parsing logic to cache 100 records at a time. This approach allows us to manage memory usage efficiently by periodically writing the processed data to a file and then clearing the cache before continuing with the next batch of records. This method ensures that the entire JSON file can be processed without exceeding memory limits, enabling us to handle files as large as 5.6 GB or more.</p><p>This approach leads to something rather intriguing from workflow perspective. It is possible to create an Event based publishing/subscription model that periodically pushes a small batch of the MRF parsed records to a Kafka or RedPanda. When coupled and integrated with Azure or AWS cloud platforms this could potentially highly scaleable search scenarios.</p><p>The example used for the actual test consisted of the following sample of the United Healthcare’s MRF file. The example of file is shortened due to 5.6GB size and only used for illustration.</p><pre>{<br>    &quot;reporting_entity_name&quot;: &quot;United HealthCare Services, Inc.&quot;,<br>    &quot;reporting_entity_type&quot;: &quot;Third-Party Administrator&quot;,<br>    &quot;last_updated_on&quot;: &quot;2024-07-01&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>&quot;provider_references&quot;:<br> [{&quot;provider_groups&quot;: [{&quot;npi&quot;: [1285746263], &quot;tin&quot;: {&quot;type&quot;: &quot;ein&quot;, &quot;value&quot;: &quot;010731399&quot;}}], &quot;provider_group_id&quot;: 0}, {&quot;provider_groups&quot;: [{&quot;npi&quot;: [1457470858], &quot;tin&quot;: {&quot;type&quot;: &quot;ein&quot;, &quot;value&quot;: &quot;208550806&quot;}}], &quot;provider_group_id&quot;: 1}, {&quot;provider_groups&quot;: [{&quot;npi&quot;: [1669460184], &quot;tin&quot;: {&quot;type&quot;: &quot;ein&quot;, &quot;value&quot;: &quot;043295025&quot;}}], &quot;provider_group_id&quot;: 2}, {&quot;provider_groups&quot;: [{&quot;npi&quot;: [0], &quot;tin&quot;: {&quot;type&quot;: &quot;ein&quot;, &quot;value&quot;: &quot;010211546&quot;}}], &quot;provider_group_id&quot;: 3}, {&quot;provider_groups&quot;: [{&quot;npi&quot;: [1013997329], &quot;tin&quot;: {&quot;type&quot;: &quot;ein&quot;, &quot;value&quot;: &quot;201830786&quot;}}], &quot;provider_group_id&quot;: 4}, {&quot;provider_groups&quot;: [{&quot;npi&quot;: [1528024585], &quot;tin&quot;: {&quot;type&quot;: &quot;ein&quot;, &quot;value&quot;: &quot;042619517&quot;}}, {&quot;npi&quot;: [0, 1629674221, 1134107436, 1326313776, 1710965074, 1013179787, 1679512792, 1821619925, 1285194480, 1912970591, 1396164877, 1811976897, 1730341686, 1255741856, 1437349529, 1013996099, 1083908685, 1134651433, 1851687586, 1619318532, 1447239439, 1538628318, 1093104408, 1962814921, 1922127166, 1982135463, 1710417563, 1205220126, 1821557695, 1194179234, 1861786972, 1386905685, 1134263502, 1184915407, 1134329691, 1144609793, 1841682127, 1578121000, 1194284240, 1245674985, 1699119354, 1538505771]<br><br>...<br>&quot;in_network&quot;: [<br> {&quot;negotiation_arrangement&quot;:&quot;ffs&quot;,&quot;name&quot;:&quot;RBC DNA HEA 35 AG 11 BLD GRP WHL BLD CMN ALLEL&quot;,&quot;billing_code_type&quot;:&quot;CPT&quot;,&quot;billing_code_type_version&quot;:&quot;2024&quot;,&quot;billing_code&quot;:&quot;0001U&quot;,&quot;description&quot;:&quot;Red blood cell antigen typing, DNA, human erythrocyte antigen gene analysis of 35 antigens from 11 blood groups, utilizing whole blood, common RBC alleles reported&quot;,&quot;negotiated_rates&quot;:[{&quot;provider_references&quot;:[1614],&quot;negotiated_prices&quot;:[{&quot;negotiated_rate&quot;:720.0,&quot;service_code&quot;:[&quot;11&quot;],<br>&quot;negotiated_type&quot;:&quot;negotiated&quot;,&quot;expiration_date&quot;:&quot;9999-12-31&quot;,<br>&quot;billing_class&quot;:&quot;professional&quot;,&quot;billing_code_modifier&quot;:[],<br>&quot;additional_information&quot;:&quot;&quot;}]},{&quot;provider_references&quot;:[1562],<br>&quot;negotiated_prices&quot;:[{&quot;negotiated_rate&quot;:720.0,&quot;service_code&quot;:[&quot;11&quot;],<br>&quot;negotiated_type&quot;:&quot;negotiated&quot;,&quot;expiration_date&quot;:&quot;9999-12-31&quot;,&quot;billing_class&quot;:&quot;professional&quot;,&quot;billing_code_modifier&quot;:[],&quot;additional_information&quot;:&quot;&quot;}]},<br>{&quot;provider_references&quot;:[560],&quot;negotiated_prices&quot;:[{&quot;negotiated_rate&quot;:720.0,&quot;service_code&quot;:[&quot;11&quot;],&quot;negotiated_type&quot;:&quot;negotiated&quot;,&quot;expiration_date&quot;:&quot;9999-12-31&quot;,&quot;billing_class&quot;:&quot;professional&quot;,&quot;billing_code_modifier&quot;:[],&quot;additional_information&quot;:&quot;&quot;}]}]}]}</pre><p>Heres the result of parsing provider_references</p><pre>Data extracted from JSON<br><br>(&#39;0&#39;, [&#39;1285746263&#39;], &#39;ein&#39;, &#39;010731399&#39;)<br>(&#39;1&#39;, [&#39;1457470858&#39;], &#39;ein&#39;, &#39;208550806&#39;)<br>(&#39;2&#39;, [&#39;1669460184&#39;], &#39;ein&#39;, &#39;043295025&#39;)<br>(&#39;3&#39;, [&#39;0&#39;], &#39;ein&#39;, &#39;010211546&#39;)<br>(&#39;4&#39;, [&#39;1013997329&#39;], &#39;ein&#39;, &#39;201830786&#39;)<br>(&#39;5&#39;, [&#39;1528024585&#39;, &#39;0&#39;, &#39;1629674221&#39;, &#39;1134107436&#39;, &#39;1326313776&#39;, &#39;1710965074&#39;, &#39;1013179787&#39;, &#39;1679512792&#39;, &#39;1821619925&#39;, &#39;1285194480&#39;, &#39;1912970591&#39;, &#39;1396164877&#39;, &#39;1811976897&#39;, &#39;1730341686&#39;, &#39;1255741856&#39;, &#39;1437349529&#39;, &#39;1013996099&#39;, &#39;1083908685&#39;])</pre><p>and the result of parsing in_network section is:</p><pre>&#39;name&#39;: &#39;RBC DNA HEA 35 AG 11 BLD GRP WHL BLD CMN ALLEL&#39;, <br> &#39;description&#39;: &#39;Red blood cell antigen typing, DNA, human erythrocyte antigen gene analysis of 35 antigens from 11 blood groups, utilizing whole blood, common RBC alleles reported&#39;, &#39;billing_code_type&#39;: &#39;CPT&#39;, &#39;billing_code&#39;: &#39;0001U&#39;, &#39;provider_group_ids&#39;: [&#39;5&#39;, &#39;8&#39;, &#39;9&#39;, &#39;10&#39;, &#39;11&#39;, &#39;12&#39;, &#39;21&#39;, &#39;23&#39;, &#39;29&#39;,<br> &#39;31&#39;, &#39;32&#39;, &#39;34&#39;, &#39;36&#39;, &#39;37&#39;, &#39;39&#39;, &#39;40&#39;, &#39;41&#39;, &#39;47&#39;, &#39;51&#39;,<br> &#39;52&#39;, &#39;53&#39;, &#39;54&#39;, &#39;55&#39;, &#39;56&#39;, &#39;57&#39;, &#39;60&#39;, &#39;61&#39;]</pre><p><strong>Example of Azure Durable Functions Orchestration</strong></p><p>To scale this solution effectively for truly large MRF files, Azure Durable Functions could be leveragedto orchestrate separate tasks for parsing provider_references and in_network sections. Here is a simplified orchestration workflow example:</p><ol><li><strong>Download and Unzip the File</strong>:</li></ol><ul><li>Use an activity function to download the zipped MRF file directly from a URL.</li><li>Another activity function can handle the unzipping of the file to Azure blob storage.</li></ul><ol><li><strong>Parse provider_references</strong>:</li></ol><ul><li>A durable activity function is triggered to parse the provider_references section. This function reads the JSON file in a streaming manner using the ijson library, extracts provider group IDs, NPIs, and TINs, and caches the results periodically to prevent memory overflow.</li></ul><ol><li><strong>Parse in_network Data</strong>:</li></ol><ul><li>Another durable activity function handles the parsing of the in_network section, focusing on extracting negotiation details, billing codes, and associated provider group IDs. This function also streams the data, processes it in batches, and saves intermediate results.</li></ul><ol><li><strong>Save and Monitor Results</strong>:</li></ol><ul><li>An orchestration function coordinates these activities, ensuring that they execute in sequence and handle retries in case of failures. The orchestration function also triggers monitoring activities to log progress and completion status to Elastic Search for better observability.</li></ul><p><strong>Azure Durable Functions Code Example</strong></p><p>Here is a basic outline for the orchestration function in Azure Durable Functions:</p><pre>import azure.functions as func<br>import azure.durable_functions as df<br><br># Orchestrator function<br>def orchestrator_function(context: df.DurableOrchestrationContext):<br>    # Step 1: Download and unzip the file<br>    download_result = yield context.call_activity(&#39;download_and_unzip_file&#39;, &#39;http://example.com/path/to/mrf.zip&#39;)<br><br>    # Step 2: Parse provider_references<br>    provider_references_result = yield context.call_activity(&#39;parse_provider_references&#39;, download_result[&#39;unzipped_file_path&#39;])<br><br>    # Step 3: Parse in_network data<br>    in_network_result = yield context.call_activity(&#39;parse_in_network&#39;, download_result[&#39;unzipped_file_path&#39;])<br><br>    # Log or store results<br>    yield context.call_activity(&#39;log_results&#39;, {&#39;provider_references&#39;: provider_references_result, &#39;in_network&#39;: in_network_result})<br><br>    return {&quot;status&quot;: &quot;Completed&quot;}<br><br># Register the orchestration<br>main = df.Orchestrator.create(orchestrator_function)</pre><p><strong>Acknowledging ChatGPT’s Contribution</strong></p><p>While developing this solution, ChatGPT was used to help generate the boilerplate code and figure out efficient ways to handle large files incrementally. The authored provided the context and specific requirements, and ChatGPT assisted in crafting the code structure, optimizing it for performance, and ensuring all edge cases were covered.</p><p>This collaboration between AI and human guidance resulted in a robust solution that can handle large MRF files effectively, using a combination of JSON schema, incremental parsing, and efficient memory management.</p><p><strong>Future Work and Challenges</strong></p><p>This implementation is just the first step in creating a comprehensive parsing solution for MRF files. One of the major challenges is dealing with truly large files — those exceeding 5.6 GB — that require periodic caching of parsed data to prevent overflow in the ijson library. Additionally, using FastAPI to upload such large files poses its own challenges, with file upload times ranging from 5 to 8 minutes.</p><p>In future articles, a full context of Azure Durable Functions will be explored to performed download of zipped archives directly from websites, splitting of tasks into individual activities, and add monitoring of the process via Elastic Search. These enhancements will further improve the scalability and efficiency of the solution, making it suitable for handling even larger and more complex MRF files.</p><p><strong>Conclusion</strong></p><p>Processing large JSON files like MRFs in the healthcare industry requires a thoughtful approach to memory management and data processing. By leveraging JSON schema, streaming libraries like ijson, and smart file handling strategies, I successfully developed a solution to handle large files efficiently. Acknowledging the role of AI tools like ChatGPT in aiding the development process is crucial, as they provide a powerful way to brainstorm, iterate, and refine code efficiently.</p><p>I hope this article helps others facing similar challenges and inspires them to explore AI-assisted development in their projects.</p><p>The GitHub source is provided here <a href="https://bit.ly/47ycFlk">https://bit.ly/47ycFlk</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea28c45e1010" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>