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 robustjsonify(response, fallback=False, verbose=True): ''' Flask's default jsonifier clobbers dict order; this preserves it; however, it falls back to regular Flask jsonify if needed. ''' robustjson = sc.sanitizejson( response, tostring=True ) + '\n' # The newline is part of Flask: https://github.com/pallets/flask/issues/1877 lenjson = len(robustjson) placeholder = '_' * ( lenjson - 3 ) # Create a placeholder of the correct length -- -3 because of ""\n which gets added flaskjson = flask_jsonify(placeholder) # Use standard Flask jsonification lenplaceholder = len(flaskjson.response[0]) if lenplaceholder == lenjson: # Lengths match, proceed flaskjson.response[0] = robustjson else: # If there's a length mismatch, fall back to regular Flask if verbose: print( 'ScirisApp: not robustifying JSON since length mismatch (%s vs. %s): %s' % (lenjson, len(flaskjson.response[0]), robustjson)) fallback = True if fallback: # Use standard Flask jsonification if anything went wrong try: flaskjson = flask_jsonify(sc.sanitizejson(response)) except Exception as E: errormsg = 'Flask jsonification of "%s" failed: %s' % (response, str(E)) raise Exception(errormsg) return flaskjson
def mpld3ify(fig, sanitize=True, jsonify=True): ''' Do all the processing steps that might be necessary to render a figure displayable ''' import mpld3 # Do this here since currently a bug that sets the wrong backend # Nothing to do if already a string if sc.isstring(fig): return fig # If it's empty or null, make a small figure if not fig: fig = pl.figure(figsize=(1, 1)) # Make a dummy plot since no legend fig.add_subplot(111) # So axis commands work fig.get_axes()[0].set_visible(False) # Turn off axes # Convert to mpld3 -- this is the big step if isinstance(fig, pl.Figure): fig = mpld3.fig_to_dict(fig) # Optionally do additional sanitization if sanitize: fig = sc.sanitizejson(fig) if jsonify and not sc.isstring(fig): fig = json.dumps(fig) # Could cause problems to jsonify a string return fig
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 getoptions(tojson=True): options = sc.odict([ ('Advertising', 'advert'), ('Education', 'educat'), ('Small business', 'smallbiz'), ('Travel', 'travel'), ('Unemployment', 'unempl'), ]) if tojson: output = sc.sanitizejson(options.keys(), tostring=False) else: output = options return output