Prepares dict with col descriptions to be JSON serializable
358374
def _description_columns_json(self, cols=None):
        
        ret = {}
        cols = cols or []
        d = {k: v for (k, v) in self.description_columns.items() if k in cols}
        for key, value in d.items():
            ret[key] = as_unicode(_(value).encode("UTF-8"))
        return ret
764508
def json_format_dict(self, data, pretty=False):
        '''  '''

        if pretty:
            return json.dumps(data, sort_keys=True, indent=2)
        else:
            return json.dumps(data)
1315836
def to_json(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True,
              pretty=False):
    
    return to_json(
      self.to_dict(
        include_keys=include_keys,
        exclude_keys=exclude_keys,
        use_default_excludes=use_default_excludes),
      pretty=pretty)
1083840
def dict_to_serialized_dict(ref, the_dict):
    
    result = {}
    for elt in list(the_dict.values()):
        if not getattr(elt, 'serialize', None):
            continue
        result[elt.uuid] = elt.serialize()
    return result
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)
36030
def dict_factory(cursor, row):
    
    out = {}
    for i, col in enumerate(cursor.description):
        out[col[0]] = row[i]
    return out
787017
def _serialize_dict(cls, data):
        '''
        
        '''
        return b64encode(zlib.compress(cPickle.dumps(data, protocol=2))).decode()
1195445
def to_dict_list(df, use_ordered_dict=True):
    
    if use_ordered_dict:
        dict = OrderedDict

    columns = df.columns
    data = list()
    for tp in itertuple(df):
        data.append(dict(zip(columns, tp)))
    return data
587807
def column_describe(table_name, col_name):
    
    col_desc = orca.get_table(table_name).get_column(col_name).describe()
    return (
        col_desc.to_json(orient='split'),
        200,
        {'Content-Type': 'application/json'})
242148
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'location') and self.location is not None:
            _dict['location'] = self.location._to_dict()
        if hasattr(self, 'text') and self.text is not None:
            _dict['text'] = self.text
        if hasattr(self, 'section_title') and self.section_title is not None:
            _dict['section_title'] = self.section_title._to_dict()
        if hasattr(self, 'table_headers') and self.table_headers is not None:
            _dict['table_headers'] = [x._to_dict() for x in self.table_headers]
        if hasattr(self, 'row_headers') and self.row_headers is not None:
            _dict['row_headers'] = [x._to_dict() for x in self.row_headers]
        if hasattr(self, 'column_headers') and self.column_headers is not None:
            _dict['column_headers'] = [
                x._to_dict() for x in self.column_headers
            ]
        if hasattr(self,
                   'key_value_pairs') and self.key_value_pairs is not None:
            _dict['key_value_pairs'] = [
                x._to_dict() for x in self.key_value_pairs
            ]
        if hasattr(self, 'body_cells') and self.body_cells is not None:
            _dict['body_cells'] = [x._to_dict() for x in self.body_cells]
        return _dict
810651
def json_to_csv(json_input):
    '''
    
    '''
    try:
        json_input = json.loads(json_input)
    except:
        pass # If loads fails, it's probably already parsed
    headers = set()
    for json_row in json_input:
        headers.update(json_row.keys())

    csv_io = StringIO.StringIO()
    csv_out = csv.DictWriter(csv_io,headers)
    csv_out.writeheader()
    for json_row in json_input:
        csv_out.writerow(json_row)
    csv_io.seek(0)
    return csv_io.read()
158774
def to_dict(self, serialize=False):
        
        if serialize:
            encode_method = json_encode_for_zendesk
        else:
            encode_method = json_encode_for_printing
        return json.loads(json.dumps(self._to_dict(serialize=serialize), default=encode_method))
109746
def _to_dict(self, serialize=False):
        
        copy_dict = self.__dict__.copy()
        for key, value in vars(self).items():
            # We want to send all ids to Zendesk always
            if serialize and key == 'id':
                continue

            # If this is a Zenpy object, convert it to a dict.
            if not serialize and isinstance(value, BaseObject):
                copy_dict[key] = copy_dict.pop(key).to_dict()

            # This object has a flag indicating it has been dirtied, so we want to send it off.
            elif serialize and getattr(value, '_dirty', False):
                continue

            # Here we have an attribute that should always be sent to Zendesk.
            elif serialize and key in self._always_dirty:
                continue

            # These are for internal tracking, so just delete.
            elif key in ('api', '_dirty_attributes', '_always_dirty', '_dirty_callback', '_dirty'):
                del copy_dict[key]

            # If the attribute has not been modified, do not send it.
            elif serialize and key not in self._dirty_attributes:
                del copy_dict[key]

            # Some reserved words are prefixed with an underscore, remove it here.
            elif key.startswith('_'):
                copy_dict[key[1:]] = copy_dict[key]
                del copy_dict[key]
        return copy_dict
806576
def prepare(self, data):
        
        result = {}

        if not self.fields:
            # No fields specified. Serialize everything.
            return data

        for fieldname, lookup in self.fields.items():
            if isinstance(lookup, SubPreparer):
                result[fieldname] = lookup.prepare(data)
            else:
                result[fieldname] = self.lookup_data(lookup, data)

        return result
924189
def toJson(self, data=None, pretty=False):
        """"""
        if data==None: data = self.attrs
        data = self.flatten(data) # don't send objects as str in json
        #if pretty:
        ret = json.dumps(data, indent=4, sort_keys=True)
        #self.inflate() # restore objects from json str data
        return ret
211738
def export_to_json(
    table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs
):
    
    # TODO: will work only if table.fields is OrderedDict

    fields = table.fields
    prepared_table = prepare_to_export(table, *args, **kwargs)
    field_names = next(prepared_table)
    data = [
        {
            field_name: _convert(value, fields[field_name], *args, **kwargs)
            for field_name, value in zip(field_names, row)
        }
        for row in prepared_table
    ]

    result = json.dumps(data, indent=indent)
    if type(result) is six.text_type:  # Python 3
        result = result.encode(encoding)

    if indent is not None:
        # clean up empty spaces at the end of lines
        result = b"\n".join(line.rstrip() for line in result.splitlines())

    return export_data(filename_or_fobj, result, mode="wb")
163241
def make_dict(self, field_values):
        ''' 
        '''
        data_dict = {}
        for key, value, field_type, converter in zip(self.field_names, field_values, self.field_types, self.type_converters):
            try:
                # We have to deal with the '-' based on the field_type
                data_dict[key] = self.dash_mapper.get(field_type, '-') if value == '-' else converter(value)
            except ValueError as exc:
                print('Conversion Issue for key:{:s} value:{:s}\n{:s}'.format(key, str(value), str(exc)))
                data_dict[key] = value
                if self._strict:
                    raise exc

        return data_dict