0
# Serialization
1
2
Multi-format serialization supporting JSON, XML, and YAML with flexible parsing from strings, bytes, or files. All FHIR resources support comprehensive serialization capabilities for data exchange and storage.
3
4
## Capabilities
5
6
### JSON Serialization
7
8
Native JSON serialization with support for FHIR-compliant JSON format and optional high-performance processing.
9
10
```python { .api }
11
# Instance methods for JSON serialization
12
def json(self, **kwargs) -> str:
13
"""
14
Serialize FHIR resource to JSON string.
15
16
Parameters:
17
- by_alias: bool - Use field aliases in output (default: None)
18
- exclude_none: bool - Exclude None/null values (default: None)
19
- exclude_comments: bool - Exclude comment fields (default: False)
20
- encoder: Callable - Custom JSON encoder function (default: None)
21
- return_bytes: bool - Return bytes instead of string (default: False)
22
23
Returns:
24
str - JSON representation of the resource
25
"""
26
27
# Class methods for JSON parsing
28
@classmethod
29
def parse_raw(cls, data: Union[str, bytes], content_type: str = None):
30
"""
31
Parse FHIR resource from JSON string or bytes.
32
33
Parameters:
34
- data: Union[str, bytes] - JSON data to parse
35
- content_type: str - Content type hint (default: application/json)
36
37
Returns:
38
FHIRAbstractModel - Parsed and validated FHIR resource
39
40
Raises:
41
ValidationError - If data doesn't conform to FHIR specification
42
"""
43
44
@classmethod
45
def parse_obj(cls, data: Dict[str, Any]):
46
"""
47
Parse FHIR resource from Python dictionary.
48
49
Parameters:
50
- data: Dict[str, Any] - Dictionary representation of FHIR resource
51
52
Returns:
53
FHIRAbstractModel - Parsed and validated FHIR resource
54
"""
55
```
56
57
**Usage Examples:**
58
59
```python
60
from fhir.resources.patient import Patient
61
from fhir.resources.humanname import HumanName
62
import json
63
64
# Create patient resource
65
patient = Patient(
66
id="patient-001",
67
active=True,
68
name=[HumanName(family="Doe", given=["John"])]
69
)
70
71
# Serialize to JSON
72
json_compact = patient.json()
73
json_pretty = patient.json(indent=2)
74
75
# Parse from JSON string
76
json_data = '{"resourceType": "Patient", "id": "123", "active": true}'
77
patient_from_json = Patient.parse_raw(json_data)
78
79
# Parse from dictionary
80
patient_dict = {
81
"resourceType": "Patient",
82
"id": "456",
83
"active": True,
84
"name": [{"family": "Smith", "given": ["Jane"]}]
85
}
86
patient_from_dict = Patient.parse_obj(patient_dict)
87
88
# Handle validation errors
89
try:
90
invalid_patient = Patient.parse_raw('{"invalid": "data"}')
91
except ValidationError as e:
92
print(f"Validation error: {e}")
93
```
94
95
### XML Serialization
96
97
XML serialization supporting FHIR XML format with full compliance to FHIR specification.
98
99
```python { .api }
100
def xml(self, **kwargs) -> str:
101
"""
102
Serialize FHIR resource to XML string.
103
104
Parameters:
105
- exclude_comments: bool - Exclude comment fields (default: False)
106
- pretty_print: bool - Format XML with indentation (default: False)
107
- xml_declaration: bool - Include XML declaration (default: True)
108
109
Returns:
110
str - XML representation of the resource
111
112
Requires:
113
lxml - Install with 'pip install fhir.resources[xml]'
114
"""
115
116
@classmethod
117
def parse_raw(cls, data: Union[str, bytes], content_type: str = "application/xml"):
118
"""
119
Parse FHIR resource from XML string or bytes.
120
121
Parameters:
122
- data: Union[str, bytes] - XML data to parse
123
- content_type: str - Must be 'application/xml' or 'text/xml'
124
125
Returns:
126
FHIRAbstractModel - Parsed and validated FHIR resource
127
"""
128
```
129
130
**Usage Examples:**
131
132
```python
133
from fhir.resources.patient import Patient
134
135
# Create patient
136
patient = Patient(
137
id="patient-001",
138
active=True
139
)
140
141
# Serialize to XML (requires lxml)
142
try:
143
xml_compact = patient.xml()
144
xml_pretty = patient.xml(pretty_print=True)
145
print(xml_pretty)
146
except ImportError:
147
print("Install lxml: pip install fhir.resources[xml]")
148
149
# Parse from XML
150
xml_data = '''<?xml version="1.0" encoding="UTF-8"?>
151
<Patient xmlns="http://hl7.org/fhir">
152
<id value="123"/>
153
<active value="true"/>
154
</Patient>'''
155
156
try:
157
patient_from_xml = Patient.parse_raw(xml_data, content_type="application/xml")
158
except ImportError:
159
print("XML parsing requires lxml")
160
```
161
162
### YAML Serialization
163
164
YAML serialization for human-readable configuration and data files.
165
166
```python { .api }
167
def yaml(self, **kwargs) -> str:
168
"""
169
Serialize FHIR resource to YAML string.
170
171
Parameters:
172
- by_alias: bool - Use field aliases in output (default: None)
173
- exclude_none: bool - Exclude None/null values (default: None)
174
- exclude_comments: bool - Exclude comment fields (default: False)
175
176
Returns:
177
str - YAML representation of the resource
178
179
Requires:
180
PyYAML - Install with 'pip install fhir.resources[yaml]'
181
"""
182
183
@classmethod
184
def parse_raw(cls, data: Union[str, bytes], content_type: str = "application/yaml"):
185
"""
186
Parse FHIR resource from YAML string or bytes.
187
188
Parameters:
189
- data: Union[str, bytes] - YAML data to parse
190
- content_type: str - Must be 'application/yaml' or 'text/yaml'
191
192
Returns:
193
FHIRAbstractModel - Parsed and validated FHIR resource
194
"""
195
```
196
197
**Usage Examples:**
198
199
```python
200
from fhir.resources.patient import Patient
201
202
patient = Patient(
203
id="patient-001",
204
active=True,
205
name=[HumanName(family="Doe", given=["John"])]
206
)
207
208
# Serialize to YAML (requires PyYAML)
209
try:
210
yaml_output = patient.yaml()
211
print(yaml_output)
212
except ImportError:
213
print("Install PyYAML: pip install fhir.resources[yaml]")
214
215
# Parse from YAML
216
yaml_data = """
217
resourceType: Patient
218
id: patient-123
219
active: true
220
name:
221
- family: Smith
222
given:
223
- Jane
224
"""
225
226
try:
227
patient_from_yaml = Patient.parse_raw(yaml_data, content_type="application/yaml")
228
except ImportError:
229
print("YAML parsing requires PyYAML")
230
```
231
232
### File Operations
233
234
Direct file parsing and writing with automatic format detection based on file extension.
235
236
```python { .api }
237
@classmethod
238
def parse_file(cls, path: Union[str, Path], **kwargs):
239
"""
240
Parse FHIR resource from file.
241
242
Parameters:
243
- path: Union[str, Path] - File path to parse
244
- content_type: str - Override content type detection
245
- encoding: str - File encoding (default: utf-8)
246
247
Returns:
248
FHIRAbstractModel - Parsed and validated FHIR resource
249
250
Supported formats:
251
- .json - JSON format
252
- .xml - XML format (requires lxml)
253
- .yaml, .yml - YAML format (requires PyYAML)
254
"""
255
256
def write_file(self, path: Union[str, Path], format: str = None, **kwargs):
257
"""
258
Write FHIR resource to file.
259
260
Parameters:
261
- path: Union[str, Path] - Output file path
262
- format: str - Override format detection ('json', 'xml', 'yaml')
263
- encoding: str - File encoding (default: utf-8)
264
- **kwargs: Format-specific options
265
"""
266
```
267
268
**Usage Examples:**
269
270
```python
271
from fhir.resources.patient import Patient
272
from pathlib import Path
273
274
patient = Patient(
275
id="patient-001",
276
active=True
277
)
278
279
# Parse from files
280
patient_json = Patient.parse_file("patient.json")
281
patient_xml = Patient.parse_file("patient.xml") # requires lxml
282
patient_yaml = Patient.parse_file("patient.yaml") # requires PyYAML
283
284
# Write to files with automatic format detection
285
patient.write_file("output.json")
286
patient.write_file("output.xml", pretty=True) # requires lxml
287
patient.write_file("output.yaml") # requires PyYAML
288
289
# Explicit format specification
290
patient.write_file("patient_data.txt", format="json", indent=2)
291
292
# Using pathlib
293
output_path = Path("data") / "patient.json"
294
patient.write_file(output_path)
295
```
296
297
### Dictionary Conversion
298
299
Convert FHIR resources to and from Python dictionaries for programmatic manipulation.
300
301
```python { .api }
302
def dict(self, **kwargs) -> Dict[str, Any]:
303
"""
304
Convert FHIR resource to Python dictionary.
305
306
Parameters:
307
- include_defaults: bool - Include fields with default values
308
- exclude_none: bool - Exclude None/null values (default: True)
309
- by_alias: bool - Use field aliases (default: True)
310
311
Returns:
312
Dict[str, Any] - Dictionary representation of the resource
313
"""
314
315
@classmethod
316
def from_dict(cls, data: Dict[str, Any], **kwargs):
317
"""
318
Create FHIR resource from Python dictionary.
319
320
Parameters:
321
- data: Dict[str, Any] - Dictionary data
322
323
Returns:
324
FHIRAbstractModel - FHIR resource instance
325
"""
326
```
327
328
**Usage Examples:**
329
330
```python
331
from fhir.resources.patient import Patient
332
333
patient = Patient(
334
id="patient-001",
335
active=True
336
)
337
338
# Convert to dictionary
339
patient_dict = patient.dict()
340
patient_dict_full = patient.dict(include_defaults=True)
341
342
# Create from dictionary
343
new_patient = Patient.from_dict(patient_dict)
344
345
# Modify dictionary and recreate
346
patient_dict["active"] = False
347
modified_patient = Patient.from_dict(patient_dict)
348
```
349
350
### Performance Options
351
352
High-performance JSON processing with optional orjson library for faster serialization.
353
354
```python { .api }
355
# Enhanced JSON performance (optional)
356
# Install with: pip install fhir.resources[orjson]
357
358
def json(self, use_orjson: bool = True, **kwargs) -> str:
359
"""
360
Serialize with optional orjson for better performance.
361
362
Parameters:
363
- use_orjson: bool - Use orjson if available (default: True)
364
365
Performance benefits:
366
- Up to 3x faster JSON serialization
367
- Lower memory usage
368
- Better handling of datetime objects
369
"""
370
```
371
372
**Usage Example:**
373
374
```python
375
from fhir.resources.patient import Patient
376
import time
377
378
patient = Patient(id="test", active=True)
379
380
# Benchmark JSON serialization
381
start = time.time()
382
for _ in range(1000):
383
json_data = patient.json() # Uses orjson if available
384
end = time.time()
385
386
print(f"Serialization time: {end - start:.3f}s")
387
```
388
389
## Types
390
391
```python { .api }
392
from typing import Union, Dict, Any, Optional
393
from pathlib import Path
394
from pydantic import ValidationError
395
396
# Type aliases for serialization methods
397
DataInput = Union[str, bytes, Dict[str, Any], Path]
398
SerializationFormat = Literal["json", "xml", "yaml"]
399
ContentType = Literal["application/json", "application/xml", "text/xml", "application/yaml", "text/yaml"]
400
401
# Common serialization errors
402
class SerializationError(Exception):
403
"""Base exception for serialization errors"""
404
405
class ValidationError(Exception):
406
"""Pydantic validation error for invalid FHIR data"""
407
```