sanitizejson#

sanitizejson(obj, verbose=True, die=False, tostring=False, custom=None, **kwargs)#

This is the main conversion function for Python data-structures into JSON-compatible data structures (note: sc.sanitizejson()/sc.jsonify() are identical).

Parameters:
  • obj (any) – almost any kind of data structure that is a combination of list, numpy.ndarray, odicts, etc.

  • verbose (bool) – level of detail to print

  • die (bool) – whether or not to raise an exception if conversion failed (otherwise, return a string)

  • tostring (bool) – whether to return a string representation of the sanitized object instead of the object itself

  • custom (dict) – custom functions for dealing with particular object types

  • kwargs (dict) – passed to json.dumps() if tostring=True

Returns:

the converted object that should be JSON compatible, or its representation as a string if tostring=True

Return type:

object (any or str)

Examples:

data = dict(a=np.random.rand(3), b=dict(foo='cat', bar='dog'))
json = sc.jsonify(data)
jsonstr = sc.jsonify(data, tostring=True, indent=2)

# Use a custom function for parsing the data
custom = {np.ndarray: lambda x: f'It was an array: {x}'}
j2 = sc.jsonify(data, custom=custom)