Custom handler for writing json file in InaSAFE.

    Criteria:
    - use indent = 2
    - Handle NULL from QGIS

    :param data: The data that will be written.
    :type data: dict

    :param filename: The file name.
    :type filename: str
489024
def write_json(data, filename):
    

    def custom_default(obj):
        if obj is None or (hasattr(obj, 'isNull') and obj.isNull()):
            return ''
        raise TypeError

    with open(filename, 'w') as json_file:
        json.dump(data, json_file, indent=2, default=custom_default)
917958
def dump(self, content, filepath, indent=4):
        
        with open(filepath, 'w') as fp:
            json.dump(content, fp, indent=indent)
1205056
def save_json(filename: str, config: Union[List, Dict]):
    
    try:
        data = json.dumps(config, sort_keys=True, indent=4)
        with open(filename, 'w', encoding='utf-8') as fdesc:
            fdesc.write(data)
            return True
    except TypeError as error:
        _LOGGER.exception('Failed to serialize to JSON: %s',
                          filename)
        raise PytradfriError(error)
    except OSError as error:
        _LOGGER.exception('Saving JSON file failed: %s',
                          filename)
        raise PytradfriError(error)
205739
def write_json_to_file(self, net_type, filename, indent='no-indent'):
    '''
    
    '''
    export_data.write_json_to_file(self, net_type, filename, indent)
1143972
def savejson(filename, datadict):
    
    for key, value in datadict.items():
        if type(value) == np.ndarray:
            datadict[key] = value.tolist()
        if type(value) == dict:
            for key2, value2 in value.items():
                if type(value2) == np.ndarray:
                    datadict[key][key2] = value2.tolist()
    with open(filename, "w") as f:
        f.write(json.dumps(datadict, indent=4))
812431
def write_dicts_to_json(self, data):
        
        with open(self.path, "w") as out:
            json.dump(
                data,  # data
                out,  # file handler
                indent=4, sort_keys=True  # pretty print
            )
495224
function writeJSON(filename, obj) {

    return new Promise(function (resolve, reject) {

      if (!Object.is(obj)) resolve(new Error('writeJSON requires the second argument to be an object'));

      _fs2['default'].writeFile(filename, JSON.stringify(obj, null, 2) + '\n', function (err) {
        if (err) reject(err);
        resolve(obj);
      });
    });
  }
501582
def json_to_file(data, filename, pretty=False):
    ''''''
    kwargs = dict(indent=4) if pretty else {}
    dirname = os.path.dirname(filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    dump = json.dumps(api.__schema__, **kwargs)
    with open(filename, 'wb') as f:
        f.write(dump.encode('utf-8'))
839820
def dumps(dict_data, ensure_ascii=True, indent=None,
          sort_keys=False, encoding='utf-8', **kwargs):
    

    return json.dumps(dict_data, default=json_default,
                      ensure_ascii=ensure_ascii, indent=indent,
                      sort_keys=sort_keys, encoding=encoding, **kwargs)
771921
def dump_json(data, indent=None):
    
    return json.dumps(data,
                      indent=indent,
                      ensure_ascii=False,
                      sort_keys=True,
                      separators=(',', ': '))
727798
def _format_json(self, ans, q):
        
        params = {}
        try: params['indent'] = int(q.get('indent')[0])
        except: pass

        return json.dumps(ans, **params)+'\n'
135370
def write_config_json(config_file, data):
    
    outfile = None
    try:
        with open(config_file, 'w') as outfile:
            json.dump(data, outfile)
    except:
        line, filename, synerror = trace()
        raise ArcRestHelperError({
                    "function": "init_config_json",
                    "line": line,
                    "filename":  filename,
                    "synerror": synerror,
                                    }
                                    )
    finally:
        outfile = None

        del outfile

        gc.collect()
486824
def tojson(val, indent=None):
    '''
    
    '''
    options = {'ensure_ascii': True}
    if indent is not None:
        options['indent'] = indent
    return (
        salt.utils.json.dumps(
            val, **options
        ).replace('<', '\\u003c')
         .replace('>', '\\u003e')
         .replace('&', '\\u0026')
         .replace("'", '\\u0027')
    )
316250
def write_output(self, data, filename=None, args=None):
        """"""
        if args:
            if not args.linejson:
                return 0
        if not filename: filename = args.linejson
        entrylist = []
        for entry in data['entries']:
            entrystring = json.dumps(entry, sort_keys=True)
            entrylist.append(entrystring)
        
        with open(str(filename), 'w') as output_file:
            output_file.write('\n'.join(entrylist))
1160848
public static String toJsonStr(JSON json, int indentFactor) {
		if (null == json) {
			return null;
		}
		return json.toJSONString(indentFactor);
	}
777613
def save_blob_as_json(filename, blob, force_write, debug):
    
    try:
        if prompt_4_overwrite(filename, force_write):
            with open(filename, 'wt') as f:
                print('%s' % json.dumps(blob, indent=4 if debug else None, separators=(',', ': '), sort_keys=True, cls=CustomJSONEncoder), file=f)
    except Exception as e:
        printException(e)
        pass
262600
def _write_json(file, contents):
    """"""
    with open(file, 'w') as f:
        return json.dump(contents, f, indent=2, sort_keys=True)