Skip to content

Commit

Permalink
Remove DandiBaseModel.json_dict
Browse files Browse the repository at this point in the history
Replace its use with
`pydantic.BaseModel.model_dump(mode='json', exclude_none=True)`
  • Loading branch information
candleindark committed Nov 21, 2023
1 parent 3b4ecf3 commit b211bfd
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 30 deletions.
2 changes: 1 addition & 1 deletion dandischema/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,4 +346,4 @@ def aggregate_assets_summary(metadata: Iterable[Dict[str, Any]]) -> dict:
len(stats.pop("tissuesample", [])) + len(stats.pop("slice", []))
) or None
stats["numberOfCells"] = len(stats.pop("cell", [])) or None
return models.AssetsSummary(**stats).json_dict()
return models.AssetsSummary(**stats).model_dump(mode="json", exclude_none=True)
32 changes: 3 additions & 29 deletions dandischema/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from copy import deepcopy
from datetime import date, datetime
from enum import Enum
import json
import os
import re
import sys
from typing import Any, Dict, List, Optional, Sequence, Type, TypeVar, Union, cast
from typing import Any, Dict, List, Optional, Sequence, Type, TypeVar, Union

from pydantic import (
UUID4,
Expand Down Expand Up @@ -66,16 +65,6 @@ def diff_models(model1: M, model2: M) -> None:
print(f"{field} is different")


def _sanitize(o: Any) -> Any:
if isinstance(o, dict):
return {_sanitize(k): _sanitize(v) for k, v in o.items()}
elif isinstance(o, (set, tuple, list)):
return type(o)(_sanitize(x) for x in o)
elif isinstance(o, Enum):
return o.value
return o


class AccessType(Enum):
"""An enumeration of access status options"""

Expand Down Expand Up @@ -360,27 +349,12 @@ class AgeReferenceType(Enum):
GestationalReference = "dandi:GestationalReference"


class HandleKeyEnumEncoder(json.JSONEncoder):
def encode(self, o: Any) -> Any:
return super().encode(_sanitize(o))


class DandiBaseModel(BaseModel):
id: Optional[str] = Field(
default=None, description="Uniform resource identifier", readOnly=True
)
schemaKey: str = Field("DandiBaseModel", readOnly=True)

def json_dict(self) -> dict:
"""
Recursively convert the instance to a `dict` of JSONable values,
including converting enum values to strings. `None` fields
are omitted.
"""
return cast(
dict, json.loads(self.json(exclude_none=True, cls=HandleKeyEnumEncoder))
)

# TODO[pydantic]: We couldn't refactor the `validator`,
# please replace it by `field_validator` manually.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-validators
Expand Down Expand Up @@ -650,13 +624,13 @@ class StandardsType(BaseType):
nwb_standard = StandardsType(
name="Neurodata Without Borders (NWB)",
identifier="RRID:SCR_015242",
).json_dict()
).model_dump(mode="json", exclude_none=True)


bids_standard = StandardsType(
name="Brain Imaging Data Structure (BIDS)",
identifier="RRID:SCR_016124",
).json_dict()
).model_dump(mode="json", exclude_none=True)


class ContactPoint(DandiBaseModel):
Expand Down

0 comments on commit b211bfd

Please sign in to comment.