How to Convert Multiple DICOM Files into a Single JSON Array

How to Convert Multiple DICOM Files into a Single JSON Array

This tutorial demonstrates how to convert multiple DICOM files into a single JSON array using C#. This approach is ideal for data engineers who need to export DICOM metadata for analytics tools, databases, or data pipelines.

Benefits of JSON Array Export

  1. Bulk Data Processing:
    • Import multiple DICOM records into databases in a single operation.
  2. Analytics Ready:
    • JSON arrays can be directly loaded into Python, Spark, or data warehouses.
  3. Compact Output:
    • Single file containing all metadata simplifies data management.

Prerequisites: Preparing the Environment

  1. Set up Visual Studio or any compatible .NET IDE.
  2. Create a new .NET 8 console application project.
  3. Install Aspose.Medical from the NuGet Package Manager.
  4. Prepare a folder containing multiple DICOM files.

Step-by-Step Guide to Convert Multiple DICOM Files to JSON Array

Step 1: Install Aspose.Medical

Add the Aspose.Medical library to your project using NuGet.

Install-Package Aspose.Medical

Step 2: Include Necessary Namespaces

Add references to the required namespaces in your code.

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

Step 3: Load Multiple DICOM Files

Load DICOM files from a folder into a collection.

string inputFolder = @"C:\DicomStudies";
string[] dicomPaths = Directory.GetFiles(inputFolder, "*.dcm");

List<DicomFile> dicomFiles = new();
foreach (string path in dicomPaths)
{
    dicomFiles.Add(DicomFile.Open(path));
}

Step 4: Extract Dataset Array

Build an array of Dataset objects from the loaded files.

Dataset[] datasets = dicomFiles
    .Select(dcm => dcm.Dataset)
    .ToArray();

Step 5: Serialize to JSON Array

Use DicomJsonSerializer.Serialize with the Dataset array.

string jsonArray = DicomJsonSerializer.Serialize(datasets, writeIndented: true);

Step 6: Save the JSON Array

Save the JSON array to a file.

File.WriteAllText("dicom_studies.json", jsonArray);
Console.WriteLine($"Exported {datasets.Length} DICOM datasets to JSON array.");

Complete Code Example

Here is a complete example demonstrating how to convert multiple DICOM files to a JSON array:

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

string inputFolder = @"C:\DicomStudies";
string outputFile = "dicom_studies.json";

// Get all DICOM files
string[] dicomPaths = Directory.GetFiles(inputFolder, "*.dcm");
Console.WriteLine($"Found {dicomPaths.Length} DICOM files.");

// Load all files
List<DicomFile> dicomFiles = new();
foreach (string path in dicomPaths)
{
    try
    {
        dicomFiles.Add(DicomFile.Open(path));
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Skipping invalid file: {Path.GetFileName(path)}");
    }
}

// Build dataset array
Dataset[] datasets = dicomFiles
    .Select(dcm => dcm.Dataset)
    .ToArray();

// Serialize to JSON array
string jsonArray = DicomJsonSerializer.Serialize(datasets, writeIndented: true);

// Save to file
File.WriteAllText(outputFile, jsonArray);

Console.WriteLine($"Successfully exported {datasets.Length} datasets to {outputFile}");

Example JSON Array Output

The output JSON array looks like this:

[
  {
    "00080005": { "vr": "CS", "Value": ["ISO_IR 100"] },
    "00100010": { "vr": "PN", "Value": [{ "Alphabetic": "DOE^JOHN" }] },
    "00100020": { "vr": "LO", "Value": ["12345"] }
  },
  {
    "00080005": { "vr": "CS", "Value": ["ISO_IR 100"] },
    "00100010": { "vr": "PN", "Value": [{ "Alphabetic": "SMITH^JANE" }] },
    "00100020": { "vr": "LO", "Value": ["67890"] }
  }
]

Processing Large Datasets with LINQ

For better memory management with large datasets, use LINQ projections:

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

string inputFolder = @"C:\LargeDicomArchive";
string outputFile = "large_export.json";

// Process files lazily to manage memory
Dataset[] datasets = Directory.GetFiles(inputFolder, "*.dcm")
    .Select(path => 
    {
        try
        {
            return DicomFile.Open(path).Dataset;
        }
        catch
        {
            return null;
        }
    })
    .Where(ds => ds != null)
    .ToArray()!;

string jsonArray = DicomJsonSerializer.Serialize(datasets, writeIndented: true);
File.WriteAllText(outputFile, jsonArray);

Console.WriteLine($"Exported {datasets.Length} datasets.");

Adding Progress Reporting

For large batches, add progress reporting:

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

string inputFolder = @"C:\DicomStudies";
string[] dicomPaths = Directory.GetFiles(inputFolder, "*.dcm");

List<Dataset> datasets = new();
int processed = 0;
int total = dicomPaths.Length;

foreach (string path in dicomPaths)
{
    try
    {
        DicomFile dcm = DicomFile.Open(path);
        datasets.Add(dcm.Dataset);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {Path.GetFileName(path)} - {ex.Message}");
    }
    
    processed++;
    if (processed % 100 == 0 || processed == total)
    {
        Console.WriteLine($"Progress: {processed}/{total} ({processed * 100 / total}%)");
    }
}

string jsonArray = DicomJsonSerializer.Serialize(datasets.ToArray(), writeIndented: true);
File.WriteAllText("export.json", jsonArray);

Console.WriteLine($"Export complete: {datasets.Count} datasets.");

Importing JSON Array into Analytics Tools

Python Example

import json
import pandas as pd

# Load the exported JSON array
with open('dicom_studies.json', 'r') as f:
    dicom_data = json.load(f)

# Convert to DataFrame for analysis
df = pd.json_normalize(dicom_data)
print(df.head())

Loading into MongoDB

// Using mongoimport
// mongoimport --db medical --collection studies --jsonArray --file dicom_studies.json

Memory Considerations

When working with very large datasets:

  1. Process in Batches: Split files into batches of 100-500 files.
  2. Stream Output: Use stream-based serialization for very large arrays.
  3. Dispose Files: Ensure DicomFile objects are disposed after extracting datasets.
// Batch processing example
int batchSize = 100;
string[] allFiles = Directory.GetFiles(inputFolder, "*.dcm");
int batchNumber = 0;

for (int i = 0; i < allFiles.Length; i += batchSize)
{
    string[] batch = allFiles.Skip(i).Take(batchSize).ToArray();
    Dataset[] datasets = batch
        .Select(path => DicomFile.Open(path).Dataset)
        .ToArray();
    
    string batchJson = DicomJsonSerializer.Serialize(datasets, writeIndented: true);
    File.WriteAllText($"batch_{batchNumber++}.json", batchJson);
}

Additional Information

  • JSON array format is ideal for bulk imports into NoSQL databases.
  • Consider compressing large JSON files for storage efficiency.
  • For streaming scenarios, consider using NDJSON (newline-delimited JSON) format instead.

Conclusion

This tutorial has shown you how to convert multiple DICOM files into a single JSON array in C# using Aspose.Medical. This approach enables efficient bulk data export for analytics, database imports, and data pipeline integration.

 English