def test_json(): sc.heading('Testing JSON read/write functions') not_jsonifiable = sc.Blobject( ) # Create an object that can't be JSON serialized print('Testing jsonifying a NON-jsonifiable object:') notjson = sc.jsonify(not_jsonifiable, die=False) # Will return a string representation sc.sanitizejson(not_jsonifiable, die=True) # Will still not die thanks to jsonpickle jsonifiable = sc.objdict().make(keys=['a', 'b'], vals=pl.rand(10)) json_obj = sc.jsonify(jsonifiable) json_str = sc.jsonify(jsonifiable, tostring=True, indent=2) # kwargs are passed to json.dumps() print('Not-a-JSON as sanitized object:') print(notjson) print('JSON as sanitized object:') print(json_obj) print('JSON as string:') print(json_str) return json_str
def to_json(self, filename=None, tostring=True, indent=2, *args, **kwargs): """ Export results as JSON. Args: filename (str): if None, return string; else, write to file Returns: A unicode string containing a JSON representation of the results, or writes the JSON file to disk """ resdict = self._make_resdict() pardict = self._make_pardict() d = {'results': resdict, 'parameters': pardict} if filename is None: output = sc.jsonify(d, tostring=tostring, indent=indent, *args, **kwargs) else: output = sc.savejson(filename=filename, obj=d, *args, **kwargs) return output
def to_json(self, filename=None, tostring=True, indent=2, verbose=False, *args, **kwargs): ''' Export results as JSON. Args: filename (str): if None, return string; else, write to file Returns: A unicode string containing a JSON representation of the results, or writes the JSON file to disk ''' d = {'t':self.tvec, 'results': self.results, 'basepars': self.basepars, 'metapars': self.metapars, 'simpars': self.base_sim.export_pars(), 'scenarios': self.scenarios } if filename is None: output = sc.jsonify(d, tostring=tostring, indent=indent, verbose=verbose, *args, **kwargs) else: output = sc.savejson(filename=filename, obj=d, indent=indent, *args, **kwargs) return output
def to_json(self, filename=None, keys=None, tostring=False, indent=2, verbose=False, *args, **kwargs): ''' Export results as JSON. Args: filename (str): if None, return string; else, write to file keys (str or list): attributes to write to json (default: results, parameters, and summary) tostring (bool): if not writing to file, whether to write to string (alternative is sanitized dictionary) indent (int): if writing to file, how many indents to use per nested level verbose (bool): detail to print args (list): passed to savejson() kwargs (dict): passed to savejson() Returns: A unicode string containing a JSON representation of the results, or writes the JSON file to disk **Examples**:: json = sim.to_json() sim.to_json('results.json') sim.to_json('summary.json', keys='summary') ''' # Handle keys if keys is None: keys = ['results', 'pars', 'summary'] keys = sc.promotetolist(keys) # Convert to JSON-compatible format d = {} for key in keys: if key == 'results': resdict = self.export_results(for_json=True) d['results'] = resdict elif key in ['pars', 'parameters']: pardict = self.export_pars() d['parameters'] = pardict elif key == 'summary': d['summary'] = dict(sc.dcp(self.summary)) else: try: d[key] = sc.sanitizejson(getattr(self, key)) except Exception as E: errormsg = f'Could not convert "{key}" to JSON: {str(E)}; continuing...' print(errormsg) if filename is None: output = sc.jsonify(d, tostring=tostring, indent=indent, verbose=verbose, *args, **kwargs) else: output = sc.savejson(filename=filename, obj=d, indent=indent, *args, **kwargs) return output
def to_json(self): ''' Return JSON-compatible representation Custom classes can't be directly represented in JSON. This method is a one-way export to produce a JSON-compatible representation of the intervention. In the first instance, the object dict will be returned. However, if an intervention itself contains non-standard variables as attributes, then its `to_json` method will need to handle those Returns: JSON-serializable representation (typically a dict, but could be anything else) ''' which = self.__class__.__name__ pars = sc.jsonify(self.input_args) output = dict(which=which, pars=pars) return output