Python json.JSONEncoder() Examples

The following are code examples for showing how to use json.JSONEncoder(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: psycopg2-for-aws-lambda   Author: iwitaly   File: test_types_extras.py    (MIT License) View Source Project 9 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'") 
Example 2
Project: twitterscraper   Author: taspinar   File: main.py    (license) View Source Project 7 votes vote down vote up
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        elif isinstance(obj, collections.Iterable):
            return list(obj)
        elif isinstance(obj, datetime):
            return obj.isoformat()
        elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):
            return dict(obj)
        elif hasattr(obj, '__dict__'):
            return {member: getattr(obj, member)
                    for member in dir(obj)
                    if not member.startswith('_') and
                    not hasattr(getattr(obj, member), '__call__')}

        return json.JSONEncoder.default(self, obj) 
Example 3
Project: inotiftpsync   Author: Major1201   File: strings.py    (license) View Source Project 7 votes vote down vote up
def to_json(o):
    import json
    from datetime import date
    from datetime import datetime

    class CJsonEncoder(json.JSONEncoder):
        def __init__(self, **kwargs):
            super(CJsonEncoder, self).__init__(**kwargs)

        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(obj, date):
                return obj.strftime("%Y-%m-%d")
            else:
                return super(CJsonEncoder, self).default(obj)
    return json.dumps(o, cls=CJsonEncoder, ensure_ascii=False) 
Example 4
Project: psycopg2-for-aws-lambda   Author: iwitaly   File: test_types_extras.py    (MIT License) View Source Project 6 votes vote down vote up
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'") 
Example 5
Project: psycopg2-for-aws-lambda   Author: iwitaly   File: test_types_extras.py    (MIT License) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'") 
Example 6
Project: psycopg2-for-aws-lambda   Author: iwitaly   File: test_types_extras.py    (MIT License) View Source Project 6 votes vote down vote up
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'") 
Example 7
Project: OpenXCAccessory   Author: openxc   File: rsu_fn.py    (license) View Source Project 6 votes vote down vote up
def get_status(self):
        jsonString = json.JSONEncoder().encode(
					  [ { "name":"RSU", "value": self.name},	
					  { "name": self.prefix+" Spaces_available","value": self.spaces_available},
                                          { "name": self.prefix+" Longitude","value":self.lon},
                                          { "name": self.prefix+" Latitude","value":self.lat},
                                          { "name": self.prefix+" Cost/hour","value":self.rate},
					  { "name":"Count", "value":self.count}])

        self.spaces_available = random.randrange(0,self.max_spaces,1);
        self.rate = random.randrange(0,20,1);
        self.count += 1
        data = json.dumps(jsonString)
        tdata = (data.replace("}, {","}\\\0{")).replace("\\","")
#        LOG.info("TDATA = " + tdata)
        return(tdata.replace("\"[","")).replace("]\"","")+chr(0)   # Adding a \0 to the end of the packet per the message format standards 
Example 8
Project: git-reviewers   Author: johnnadratowski   File: shell.py    (license) View Source Project 6 votes vote down vote up
def write_json(output, end='', raw=False, file=None, flush=False):
    file = file or sys.stdout

    if len(output) == 1:
        output = output[0]

    if raw:
        json.dump(output, file, separators=(',', ':'), cls=JSONEncoder)
    else:
        json.dump(output, file, indent=4, sort_keys=True, cls=JSONEncoder)

    if flush:
        file.flush()

    if end:
        write_output(file, '', end=end, sep='', flush=flush) 
Example 9
Project: baka   Author: baka-framework   File: renderers.py    (license) View Source Project 6 votes vote down vote up
def default(self, o):
        # for Enum Type
        if isinstance(o, enum.Enum):
            return o.value

        # for Enum Select Integer
        if isinstance(o, EnumInt):
            return o.key

        if isinstance(o, (datetime, date)):
            return o.isoformat()

        if isinstance(o, Decimal):
            return _number_str(o)

        if isinstance(o, ObjectId):
            return str(o)

        return super(JSONEncoder, self).default(o) 
Example 10
Project: episode-miner   Author: estnltk   File: event_sequences.py    (license) View Source Project 6 votes vote down vote up
def to_json(self):
        """Serializes event sequences using json.
        
        Returns
        -------
        str
            json serialization of self. 
        """
        class EventEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Event):
                    return [obj.event_type, obj.event_time]
                if isinstance(obj, EventSequence):
                    return obj.sequence_of_events
                return json.JSONEncoder.default(self, obj)
        
        return json.dumps(self, ensure_ascii=False, cls=EventEncoder) 
Example 11
Project: plone.server   Author: plone   File: renderers.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        elif isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, type):
            return obj.__module__ + '.' + obj.__name__
        elif isinstance(obj, InterfaceClass):
            return [x.__module__ + '.' + x.__name__ for x in obj.__iro__]  # noqa
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        if isinstance(obj, PermissionSetting):
            return obj.getName()
        if callable(obj):
            return obj.__module__ + '.' + obj.__name__
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj) 
Example 12
Project: geo-tools   Author: Major1201   File: strings.py    (license) View Source Project 6 votes vote down vote up
def to_json(o):
    import json
    from datetime import date
    from datetime import datetime

    class CJsonEncoder(json.JSONEncoder):
        def __init__(self, **kwargs):
            super(CJsonEncoder, self).__init__(**kwargs)

        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(obj, date):
                return obj.strftime("%Y-%m-%d")
            else:
                return super(CJsonEncoder, self).default(obj)
    return json.dumps(o, cls=CJsonEncoder, ensure_ascii=False) 
Example 13
Project: wizard   Author: honor100   File: util.py    (license) View Source Project 6 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.isoformat()
        if isinstance(o, datetime.date):
            return o.isoformat()
        if isinstance(o, datetime.time):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return str(o)
        return json.JSONEncoder.default(self, o)
# ????? json.dumps(yourobj, cls=DateTimeEncoder)

# class DecimalEncoder(json.JSONEncoder):
#     def _iterencode(self, o, markers=None):
#         if isinstance(o, decimal.Decimal):
#             # wanted a simple yield str(o) in the next line,
#             # but that would mean a yield on the line with super(...),
#             # which wouldn't work (see my comment below), so...
#             return (str(o) for o in [o])
#         return super(DecimalEncoder, self)._iterencode(o, markers) 
Example 14
Project: irida-miseq-uploader   Author: phac-nml   File: Sample.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):

            if isinstance(obj, Sample):
                sample_dict = dict(obj.get_dict())
                # get sample dict and make a copy of it
                sample_dict.pop("sampleProject")
                if "sequencerSampleId" in sample_dict:
                    # if the sample ID field is populated, then we've just Finished
                    # reading the run from disk and we're preparing to send data
                    # to the server. The server is using the sample ID field as the
                    # name of the sample, so overwrite whatever we *were* using to
                    # find files with the sample ID field.
                    sample_dict["sampleName"] = sample_dict["sequencerSampleId"]
                return sample_dict
            else:
                return json.JSONEncoder.default(self, obj) 
Example 15
Project: guillotina   Author: plone   File: renderers.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        elif isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, type):
            return obj.__module__ + '.' + obj.__name__
        elif isinstance(obj, InterfaceClass):
            return [x.__module__ + '.' + x.__name__ for x in obj.__iro__]  # noqa
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        if isinstance(obj, PermissionSetting):
            return obj.get_name()
        if callable(obj):
            return obj.__module__ + '.' + obj.__name__
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)


# b/w compat import 
Example 16
Project: incubator-airflow-old   Author: apache   File: json.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        # convert dates and numpy objects in a json serializable format
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif type(obj) in (np.int_, np.intc, np.intp, np.int8, np.int16,
                           np.int32, np.int64, np.uint8, np.uint16,
                           np.uint32, np.uint64):
            return int(obj)
        elif type(obj) in (np.bool_,):
            return bool(obj)
        elif type(obj) in (np.float_, np.float16, np.float32, np.float64,
                           np.complex_, np.complex64, np.complex128):
            return float(obj)

        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj) 
Example 17
Project: qzig   Author: Seluxit   File: util.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        if type(obj) is value.ValuePermission:
            return obj.value
        if type(obj) is value.ValueStatus:
            return obj.value
        if type(obj) is state.StateType:
            return obj.value
        if type(obj) is state.StateStatus:
            return obj.value
        if type(obj) is value.ValueNumberType:
            return obj.__dict__
        if type(obj) is value.ValueStringType:
            return obj.__dict__
        if type(obj) is status.StatusType:
            return obj.value
        if type(obj) is status.StatusLevel:
            return obj.value
        # if type(obj) is value.ValueSetType:
        #    return obj.__dict__
        # if type(obj) is value.ValueBlobType:
        #    return obj.__dict__
        # if type(obj) is value.ValueXmlType:
        #    return obj.__dict__
        # return json.JSONEncoder.default(self, obj) 
Example 18
Project: ShelbySearch   Author: Agentscreech   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertQuotedEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'") 
Example 19
Project: ShelbySearch   Author: Agentscreech   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertQuotedEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'") 
Example 20
Project: userbase-sns-lambda   Author: fartashh   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 21
Project: userbase-sns-lambda   Author: fartashh   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 22
Project: userbase-sns-lambda   Author: fartashh   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 23
Project: userbase-sns-lambda   Author: fartashh   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 24
Project: userbase-sns-lambda   Author: fartashh   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 25
Project: userbase-sns-lambda   Author: fartashh   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 26
Project: PyMiniRacer   Author: sqreen   File: test_call.py    (license) View Source Project 6 votes vote down vote up
def test_call_custom_encoder(self):

        # Custom encoder for dates
        class CustomEncoder(json.JSONEncoder):

            def default(self, obj):
                if isinstance(obj, datetime):
                    return obj.isoformat()

                return json.JSONEncoder.default(self, obj)

        now = datetime.now()
        js_func = """var f = function(args) {
            return args;
        }"""
        self.mr.eval(js_func)

        self.assertEqual(self.mr.call('f', now, encoder=CustomEncoder),
                         now.isoformat()) 
Example 27
Project: nist_mni_pipelines   Author: vfonov   File: structures.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, MriTransform):
            return {'name':obj.name,
                    'xfm' :obj.xfm,
                    'xfm_f':obj.xfm_f,
                    'xfm_inv' :obj.xfm_inv,
                    'xfm_f_inv':obj.xfm_f_inv,
                    'prefix':obj.prefix
                   }
        elif isinstance(obj, MriDataset):
            return {'name':obj.name,
                    'scan':obj.scan,
                    'mask':obj.mask,
                    'scan_f':obj.scan_f,
                    'mask_f':obj.mask_f,
                    'prefix':obj.prefix,
                    'add':obj.add,
                    'add_f':obj.add_f,
                    'group':obj.group,
                    'grading':obj.grading,
                   }
         # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

# kate: space-indent on; indent-width 4; indent-mode python;replace-tabs on;word-wrap-column 80;show-tabs on 
Example 28
Project: nist_mni_pipelines   Author: vfonov   File: structures.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, MriTransform):
            return {'name':obj.name,
                    'xfm' :obj.xfm,
                    'xfm_f':obj.xfm_f,
                    'xfm_inv' :obj.xfm_inv,
                    'xfm_f_inv':obj.xfm_f_inv,
                    'prefix':obj.prefix
                   }
        elif isinstance(obj, MriDataset):
            return {'name':obj.name,
                    'scan':obj.scan,
                    'mask':obj.mask,
                    'scan_f':obj.scan_f,
                    'mask_f':obj.mask_f,
                    'prefix':obj.prefix,
                    'add':obj.add,
                    'add_f':obj.add_f
                   }
         # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)



# kate: space-indent on; indent-width 4; indent-mode python;replace-tabs on;word-wrap-column 80;show-tabs on 
Example 29
Project: plugin.video.netflix   Author: asciidisco   File: MSL.py    (license) View Source Project 6 votes vote down vote up
def __save_msl_data(self):
        """
        Saves the keys and tokens in json file
        :return:
        """
        data = {
            "encryption_key": base64.standard_b64encode(self.encryption_key),
            'sign_key': base64.standard_b64encode(self.sign_key),
            'tokens': {
                'mastertoken': self.mastertoken
            }
        }
        serialized_data = json.JSONEncoder().encode(data)
        self.save_file(
            msl_data_path=self.kodi_helper.msl_data_path,
            filename='msl_data.json',
            content=serialized_data) 
Example 30
Project: Price-Comparator   Author: Thejas-1   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
Example 31
Project: atg-commerce-iaas   Author: oracle   File: manageprojects.py    (license) View Source Project 6 votes vote down vote up
def load_project_data(project_name):
    """
    Load project data from properties file
    """    
    
    global identity_domain
    global username
    global image_name    
    global os_project_name
    global os_image_name      
    data_type = "project"
    
    identity_domain = orchestration_helper.get_config_item(project_name, project_name, 'identity_domain', data_type)
    username = orchestration_helper.get_config_item(project_name, project_name, 'username', data_type)
    image_name = orchestration_helper.get_config_item(project_name, project_name, 'image_name', data_type)
    os_project_name = orchestration_helper.get_config_item(project_name, project_name, 'openstack_project', data_type)
    os_image_name = orchestration_helper.get_config_item(project_name, project_name, 'openstack_image_name', data_type)    
    
    projdata = {'opc': {'Domain': identity_domain, 'username': username, 'image': image_name}, 'openstack': {'os_project_name': os_project_name, 'os_image_name': os_image_name}}
    return (json.JSONEncoder().encode(projdata)) 
Example 32
Project: _   Author: zengchunyun   File: rabb.py    (license) View Source Project 6 votes vote down vote up
def format_list(json_list, columns, args, options):
    format = options.format
    formatter = None
    if format == "raw_json":
        output(json_list)
        return
    elif format == "pretty_json":
        enc = json.JSONEncoder(False, False, True, True, True, 2)
        output(enc.encode(json.loads(json_list)))
        return
    else:
        formatter = FORMATS[format]
    assert_usage(formatter != None,
                 "Format {0} not recognised".format(format))
    formatter_instance = formatter(columns, args, options)
    formatter_instance.display(json_list) 
Example 33
Project: py   Author: stencila   File: host_http_server.py    (license) View Source Project 6 votes vote down vote up
def default(self, object):
        try:
            iterable = iter(object)
        except TypeError:
            pass
        else:
            return list(iterable)

        try:
            properties = object.__dict__
        except AttributeError:
            pass
        else:
            return dict((key, value) for key, value in properties.items() if not key.startswith('_'))

        return JSONEncoder.default(self, object) 
Example 34
Project: nmbs-realtime-feed   Author: datamindedbe   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'") 
Example 35
Project: nmbs-realtime-feed   Author: datamindedbe   File: test_types_extras.py    (license) View Source Project 6 votes vote down vote up
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'") 
Example 36
Project: shakecast   Author: usgs   File: objects.py    (license) View Source Project 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') 
                                and x != 'metadata' and x != '_sa_instance_state']:
                data = obj.__getattribute__(field)

                if isinstance(data, types.MethodType):
                    continue

                try:
                    json.dumps(data) # this will fail on non-encodable values, like other classes
                    fields[field] = data
                except TypeError:
                    try:
                        fields[field] = [str(d) for d in data]
                    except:
                        fields[field] = None
                except UnicodeEncodeError:
                    fields[field] = 'Non-encodable'
            # a json-encodable dict
            return fields
    
        return json.JSONEncoder.default(self, obj) 
Example 37
Project: rca-evaluation   Author: sieve-microservices   File: export_metrics.py    (license) View Source Project 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        return json.JSONEncoder.default(self, obj) 
Example 38
Project: python-libjuju   Author: juju   File: facade.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, Type):
            return obj.serialize()
        return json.JSONEncoder.default(self, obj) 
Example 39
Project: cellranger   Author: 10XGenomics   File: safe_json.py    (license) View Source Project 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray) and obj.ndim == 1:
                return obj.tolist()
        elif isinstance(obj, np.generic):
            return obj.item()
        return json.JSONEncoder.default(self, obj) 
Example 40
Project: data_pipeline   Author: Yelp   File: frozendict_json_encoder.py    (license) View Source Project 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, frozendict):
            return dict(obj)
        return json.JSONEncoder.default(self, obj) 
Example 41
Project: astrobase   Author: waqasbhatti   File: checkplotserver_handlers.py    (MIT License) View Source Project 5 votes vote down vote up
def default(self, obj):

        if isinstance(obj, ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return obj.decode()
        else:
            return json.JSONEncoder.default(self, obj)

# this replaces the default encoder and makes it so Tornado will do the right
# thing when it converts dicts to JSON when a
# tornado.web.RequestHandler.write(dict) is called. 
Example 42
Project: sketch-components   Author: ibhubs   File: svg.py    (license) View Source Project 5 votes vote down vote up
def simplify(self, precision):
        return self.segments(precision)


# overwrite JSONEncoder for svg classes which have defined a .json() method 
Example 43
Project: sketch-components   Author: ibhubs   File: svg.py    (license) View Source Project 5 votes vote down vote up
def default(self, obj):
        if not isinstance(obj, tuple(svgClass.values() + [Svg])):
            return json.JSONEncoder.default(self, obj)

        if not hasattr(obj, 'json'):
            return repr(obj)

        return obj.json()


# Code executed on module load #
# SVG tag handler classes are initialized here
# (classes must be defined before) 
Example 44
Project: Flask_Blog   Author: sugarguo   File: views.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj) 
Example 45
Project: Flask_Blog   Author: sugarguo   File: views.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj) 
Example 46
Project: code   Author: ActiveState   File: recipe-580664.py    (MIT License) View Source Project 5 votes vote down vote up
def default(self, obj):
        if type(obj) in self.addedtypes:
            return self.addedtypes[type(obj)].encode(obj) 
        return json.JSONEncoder.default(self, obj) 
Example 47
Project: code   Author: ActiveState   File: recipe-578696.py    (MIT License) View Source Project 5 votes vote down vote up
def default(self, obj):
            if isinstance(obj, smallDuck):
                return { obj.__class__.__name__ : obj.__dict__ }
            return json.JSONEncoder.default(self, obj) 
Example 48
Project: Location_Assistance   Author: KamalAwasthi   File: views.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def search(request):
    current_username=request.POST.get('username')
    try:
        user=User.objects.get(username=current_username)
        python_object = {'flag':'True',
                        'userName': user.username,
                        'first_name': user.first_name,
                        'last_name': user.last_name}
    except Exception as e:
        python_object = {'flag':'False'}
    datatosend=json.JSONEncoder().encode(python_object)
    return HttpResponse(datatosend)

#views for save_settings table 
Example 49
Project: Location_Assistance   Author: KamalAwasthi   File: views.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def add_friends(request):
    current_username = request.POST.get('username')
    current_friendList = request.POST.get('friendList')
    try:
        username=User.objects.get(username=current_username)
    except Exception as e:
        python_object = {'status':'203'}
        datatosend=json.JSONEncoder().encode(python_object)
        return HttpResponse(datatosend)
    json_obj = json.loads(current_friendList)
    ol=[]
    try:
        existingUser = FriendList.objects.get(user__username = username)
        user_friends = existingUser.getfoo()
        for c in user_friends:
            c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
            # print type(c)
            ol.append(c)
        for c in json_obj:
            c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
            ol.append(c)
        existingUser.friendList = json.dumps(ol)
        existingUser.save()
        python_object = {'status':'200'}
    except:
        friend = FriendList(user = username)
        friend.setfoo(current_friendList) 
        friend.save()
        python_object = {'status':'200'}
    datatosend=json.JSONEncoder().encode(python_object)
    return HttpResponse(datatosend) 
Example 50
Project: autolab_core   Author: BerkeleyAutomation   File: json_serialization.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def default(self, obj):
        """Converts an ndarray into a dictionary for efficient serialization.

        The dict has three keys:
        - dtype : The datatype of the array as a string.
        - shape : The shape of the array as a tuple.
        - __ndarray__ : The data of the array as a list.

        Parameters
        ----------
        obj : :obj:`numpy.ndarray`
            The ndarray to encode.

        Returns
        -------
        :obj:`dict`
            The dictionary serialization of obj.
        
        Raises
        ------
        TypeError
            If obj isn't an ndarray.
        """
        if isinstance(obj, np.ndarray):
            return dict(__ndarray__=obj.tolist(),
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        # Let the base class default method raise the TypeError
        return _json.JSONEncoder(self, obj)