Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
49 lines (31 sloc) 1.02 KB
"""A method for serializing values to JSON."""
from pathlib import Path
import typing
from typeclasses import typeclass
T = typing.TypeVar('T') # pylint: disable=invalid-name
def to_json(value: T) -> str: # pylint: disable=unused-argument
"""Serialize a value to JSON."""
def _to_json_none(_):
return 'null'
def _to_json_bool(value):
return 'true' if value else 'false'
def _to_json_string(string):
return f'"{str(string)}"'
def _to_json_number(number):
return str(number)
@to_json.instance(typing.Mapping, protocol=True)
def _to_json_mapping(mapping):
members = ','.join(f'"{k}":{to_json(v)}' for k, v in mapping.items())
return f'{{{members}}}'
@to_json.instance(typing.Iterable, protocol=True)
def _to_json_iterable(iterable):
items = ','.join(to_json(x) for x in iterable)
return f'[{items}]'
You can’t perform that action at this time.