Skip to content

Commit 0f470c0

Browse files
committed
Add serialization for the dataclass models
Signed-off-by: tdruez <[email protected]>
1 parent 9000cd6 commit 0f470c0

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

dje/outputs.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
# See https://aboutcode.org for more information about AboutCode FOSS projects.
77
#
88

9+
import dataclasses
910
import json
1011
import re
1112
from datetime import UTC
@@ -406,3 +407,29 @@ def get_openvex_document(product):
406407
tooling=f"DejaCode-{dejacode_version}",
407408
statements=get_openvex_statements(product),
408409
)
410+
411+
412+
def to_json_key(field_name):
413+
"""
414+
- field_id -> @id
415+
- field_context -> @context
416+
"""
417+
prefix = "field_"
418+
if field_name.startswith(prefix):
419+
return "@" + field_name.removeprefix(prefix)
420+
return field_name
421+
422+
423+
def openvex_dict_factory(fields):
424+
"""Dict factory for dataclasses.asdict that converts field names to JSON keys."""
425+
return {to_json_key(name): value for name, value in fields}
426+
427+
428+
def get_openvex_document_json(product, indent=2):
429+
openvex_document = get_openvex_document(product)
430+
openvex_document_dict = dataclasses.asdict(
431+
openvex_document,
432+
dict_factory=openvex_dict_factory,
433+
)
434+
openvex_document_json = json.dumps(openvex_document_dict, indent=indent)
435+
return openvex_document_json

dje/views.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2441,11 +2441,8 @@ class ExportOpenVEXView(
24412441
BaseDetailView,
24422442
):
24432443
def get(self, request, *args, **kwargs):
2444-
import json
2445-
24462444
product = self.get_object()
2447-
openvex_document = outputs.get_openvex_document(product)
2448-
openvex_document_json = json.dumps(openvex_document.__dict__, indent=2)
2445+
openvex_document_json = outputs.get_openvex_document_json(product)
24492446
filename = outputs.get_filename(product, extension="openvex.json")
24502447

24512448
return outputs.get_attachment_response(

0 commit comments

Comments
 (0)