Python json.JSONEncoder() Examples

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

Example 1
Project: QCElemental   Author: MolSSI   File: serialization.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, obj: Any) -> Any:
        try:
            return pydantic_encoder(obj)
        except TypeError:
            pass

        if isinstance(obj, np.ndarray):
            if obj.shape:
                data = {"_nd_": True, "dtype": obj.dtype.str, "data": np.ascontiguousarray(obj).tobytes().hex()}
                if len(obj.shape) > 1:
                    data["shape"] = obj.shape
                return data

            else:
                # Converts np.array(5) -> 5
                return obj.tolist()

        return json.JSONEncoder.default(self, obj) 
Example 2
Project: quart   Author: pgjones   File: __init__.py    MIT License 6 votes vote down vote up
def dumps(object_: Any, app: Optional["Quart"] = None, **kwargs: Any) -> str:
    json_encoder: Type[json.JSONEncoder] = JSONEncoder
    if app is None and _app_ctx_stack.top is not None:  # has_app_context requires a circular import
        app = current_app._get_current_object()

    if app is not None:
        json_encoder = app.json_encoder
        if _request_ctx_stack.top is not None:  # has_request_context requires a circular import
            blueprint = app.blueprints.get(request.blueprint)
            if blueprint is not None and blueprint.json_encoder is not None:
                json_encoder = blueprint.json_encoder
        kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])
        kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])
    kwargs.setdefault("sort_keys", True)
    kwargs.setdefault("cls", json_encoder)

    return json.dumps(object_, **kwargs) 
Example 3
Project: twitterscraper   Author: taspinar   File: main.py    MIT License 6 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, dt.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 4
Project: certidude   Author: laurivosandi   File: decorators.py    MIT License 6 votes vote down vote up
def default(self, obj):
        from certidude.user import User
        if isinstance(obj, ipaddress._IPAddressBase):
            return str(obj)
        if isinstance(obj, set):
            return tuple(obj)
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
        if isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        if isinstance(obj, timedelta):
            return obj.total_seconds()
        if isinstance(obj, types.GeneratorType):
            return tuple(obj)
        if isinstance(obj, User):
            return dict(name=obj.name, given_name=obj.given_name,
                surname=obj.surname, mail=obj.mail)
        return json.JSONEncoder.default(self, obj) 
Example 5
Project: python-esppy   Author: sassoftware   File: plotting.py    Apache License 2.0 6 votes vote down vote up
def default(self, obj):
        '''
        Convert objects unrecognized by the default encoder

        Parameters
        ----------
        obj : any
           Arbitrary object to convert

        Returns
        -------
        any
           Python object that JSON encoder will recognize

        '''
        if isinstance(obj, (float, np.float64)):
            return float(obj)
        if isinstance(obj, (long, np.int64)):
            return long(obj)
        if isinstance(obj, (int, np.int32)):
            return int(obj)
        return json.JSONEncoder.default(self, obj) 
Example 6
Project: aioworkers   Author: aioworkers   File: formatter.py    Apache License 2.0 6 votes vote down vote up
def __init__(self):
        import json
        convs = []
        for score, klass, conv in self.converters:
            if isinstance(klass, str):
                klass = import_name(klass)
            convs.append((score, klass, conv))

        class Encoder(json.JSONEncoder):
            def default(self, o):
                for score, klass, conv in convs:
                    if isinstance(o, klass):
                        return conv(o)
                return super().default(o)

        self._encoder = Encoder
        self._loads = json.loads
        self._dumps = json.dumps 
Example 7
Project: py   Author: stencila   File: host_http_server.py    Apache License 2.0 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 8
Project: pyramid-hypernova   Author: Yelp   File: tweens.py    MIT License 6 votes vote down vote up
def configure_hypernova_batch(registry, request):
    get_batch_url = registry.settings['pyramid_hypernova.get_batch_url']

    plugins = registry.settings.get('pyramid_hypernova.plugins', [])
    plugin_controller = PluginController(plugins)

    batch_request_factory = registry.settings.get(
        'pyramid_hypernova.batch_request_factory',
        BatchRequest,
    )

    json_encoder = registry.settings.get('pyramid_hypernova.json_encoder', JSONEncoder())

    return batch_request_factory(
        batch_url=get_batch_url(),
        plugin_controller=plugin_controller,
        json_encoder=json_encoder,
        pyramid_request=request,
    ) 
Example 9
Project: pyramid-hypernova   Author: Yelp   File: request_test.py    MIT License 6 votes vote down vote up
def test_successful_send_asynchronous(self, mock_fido_fetch, mock_requests_post):
        mock_fido_fetch.return_value.wait.return_value.code = 200
        mock_fido_fetch.return_value.wait.return_value.json.return_value = 'ayy lmao'

        query = HypernovaQuery(TEST_JOB_GROUP, 'google.com', JSONEncoder(), False, {'header1': 'value1'})
        query.send()

        mock_fido_fetch.assert_called_once_with(
            url='google.com',
            method='POST',
            headers={'header1': ['value1'], 'Content-Type': ['application/json']},
            body=mock.ANY,
        )
        mock_requests_post.assert_not_called()

        assert query.json() == 'ayy lmao' 
Example 10
Project: pyramid-hypernova   Author: Yelp   File: request_test.py    MIT License 6 votes vote down vote up
def test_error_status_code_send_asynchronous(self, mock_fido_fetch, mock_requests_post):
        mock_fido_fetch.return_value.wait.return_value.code = 504
        mock_fido_fetch.return_value.wait.return_value.body = b'<h1>504 Bad Gateway</h1>'
        mock_fido_fetch.return_value.wait.return_value.json.side_effect = AssertionError()

        query = HypernovaQuery(TEST_JOB_GROUP, 'google.com', JSONEncoder(), False, {})
        query.send()

        mock_fido_fetch.assert_called_once()
        mock_requests_post.assert_not_called()

        with pytest.raises(HypernovaQueryError) as exc_info:
            query.json()
        assert str(exc_info.value) == (
            'Received response with status code 504 from Hypernova. Response body:\n'
            '<h1>504 Bad Gateway</h1>'
        ) 
Example 11
Project: viewer-demo   Author: CCI-Tools   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def default(self, obj):
        """
        If input object is an ndarray it will be converted into a dict
        holding dtype, shape and the data, base64 encoded.
        """
        if isinstance(obj, numpy.ndarray):
            if obj.flags['C_CONTIGUOUS']:
                obj_data = obj.data
            else:
                cont_obj = numpy.ascontiguousarray(obj)
                assert (cont_obj.flags['C_CONTIGUOUS'])
                obj_data = cont_obj.data
            data_b64 = base64.b64encode(obj_data)
            return dict(data=data_b64.decode('unicode_escape'),
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj) 
Example 12
Project: historia   Author: acrosman   File: historia_json_encoder.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
         try:
             return obj.to_dict()
         except AttributeError as err:
             return json.JSONEncoder.default(self, obj) 
Example 13
Project: dauber   Author: OpenDataAnalytics   File: zmq.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        for cls, func in self.class_map.items():
            if isinstance(obj, cls):
                return func(obj)

        return json.JSONEncoder.default(self, obj) 
Example 14
Project: tintri-python-sdk   Author: Tintri   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if o is None: return None
        else: return o.__dict__

#class TintriJSONEncoder(json.JSONEncoder): 
Example 15
Project: QCElemental   Author: MolSSI   File: serialization.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj: Any) -> Any:
        try:
            return pydantic_encoder(obj)
        except TypeError:
            pass

        if isinstance(obj, np.ndarray):
            if obj.shape:
                return obj.ravel().tolist()
            else:
                return obj.tolist()

        return json.JSONEncoder.default(self, obj) 
Example 16
Project: Paradrop   Author: ParadropLabs   File: chute_api.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            return repr(o) 
Example 17
Project: Paradrop   Author: ParadropLabs   File: chute_api.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            return o.__dict__ 
Example 18
Project: mimic   Author: googlearchive   File: control_test.py    Apache License 2.0 5 votes vote down vote up
def setUp(self, tree=None):
    test_util.InitAppHostingApi()
    self.SetUpApplication(tree)
    # these are updated after StartResponse is called
    self._status = None
    self._headers = None
    self._output = ''

    # consistent JSON output for tests
    common.config.JSON_ENCODER = json.JSONEncoder()
    common.config.JSON_ENCODER.indent = None
    common.config.JSON_ENCODER.sort_keys = True

    common.config.ALLOWED_USER_CONTENT_HOSTS = None 
Example 19
Project: rowgenerators   Author: Metatab   File: json.py    MIT License 5 votes vote down vote up
def default(self, obj):
         from rowgenerators.valuetype import DateTimeVT, DateVT, TimeVT

         if isinstance(obj, (DateTimeVT, DateVT, TimeVT) ):
             return str(obj)

         # Let the base class default method raise the TypeError
         try:
            return json.JSONEncoder.default(self, obj)
         except TypeError as e:
             raise TypeError(DateTimeVT,type(obj)) 
Example 20
Project: pySymProxy   Author: inbilla   File: mainhandler.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if callable(getattr(obj, 'encodeJSON', None)):
            return obj.encodeJSON()
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj) 
Example 21
Project: hepaccelerate   Author: hepaccelerate   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, Histogram):
            return obj.__dict__
        return json.JSONEncoder.default(self, obj) 
Example 22
Project: matchminer-engine   Author: dfci   File: schema.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def schema_hash(schema):
    class Encoder(json.JSONEncoder):
        def default(self, o):
            return repr(o)

    _hash = hash(json.dumps(cast_keys_to_strings(schema),
                            cls=Encoder, sort_keys=True))

    return _hash 
Example 23
Project: CTask   Author: yangmv   File: public.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.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 24
Project: crashstats-tools   Author: willkg   File: utils.py    Mozilla Public License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S.%f")
        return json.JSONEncoder.default(self, obj) 
Example 25
Project: RainbowBrackets   Author: absop   File: main.py    MIT License 5 votes vote down vote up
def pprint(cls, obj):
        class setEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, set):
                    return sorted(obj)
                return json.JSONEncoder.default(self, obj)

        if cls.debug:
            print("RainbowBrackets:", json.dumps(obj,
                cls=setEncoder, indent=4,
                sort_keys=True, ensure_ascii=False)) 
Example 26
Project: libra-client   Author: yuan-xy   File: json_print.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, bytes):
            return obj.hex()
        return json.JSONEncoder.default(self, obj) 
Example 27
Project: stoq   Author: PUNCH-Cyber   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def default(self, o) -> Any:
        if isinstance(o, bytes):
            return UnicodeDammit(o).unicode_markup  # type: ignore
        elif isinstance(o, datetime.datetime):
            return str(o)
        elif isinstance(o, set):
            return list(o)
        try:
            return vars(o)
        except Exception:
            pass
        return json.JSONEncoder.default(self, o) 
Example 28
Project: zamia-prolog   Author: gooofy   File: logic.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        
        if isinstance (o, JSONLogic):
            return o.to_dict()

        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            import pdb; pdb.set_trace() 
Example 29
Project: Flask_Blog   Author: sugarguo   File: views.py    GNU General Public License v3.0 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 30
Project: Flask_Blog   Author: sugarguo   File: views.py    GNU General Public License v3.0 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 31
Project: siphon-cli   Author: getsiphon   File: __init__.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            fmt = '%Y-%m-%dT%H:%M:%S'
            return obj.strftime(fmt)

        return json.JSONEncoder.default(self, obj) 
Example 32
Project: sphinxcontrib-excel-table   Author: hackerain   File: excel_table.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.date):
            date_string = obj.strftime('%Y-%m-%d')
            return date_string
        if isinstance(obj, datetime.datetime):
            datetime_string = obj.strftime("%Y-%m-%d %H:%M:%S")
            return datetime_string
        return json.JSONEncoder.default(self, obj) 
Example 33
Project: splunk-thehive   Author: daniel-gallagher   File: models.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, JSONSerializable):
            return o.__dict__
        else:
            return json.JSONEncoder.encode(self, o) 
Example 34
Project: Autoenv   Author: intelligent-control-lab   File: logger.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, type):
            return {'$class': o.__module__ + "." + o.__name__}
        elif isinstance(o, Enum):
            return {'$enum': o.__module__ + "." + o.__class__.__name__ + '.' + o.name}
        return json.JSONEncoder.default(self, o) 
Example 35
Project: spotify-tensorflow   Author: spotify   File: example_decoders.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
            if isinstance(obj, np.ndarray):
                return obj.tolist()
            if isinstance(obj, bytes):
                return obj.decode()
            return json.JSONEncoder.default(self, obj) 
Example 36
Project: datasette   Author: simonw   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, sqlite3.Row):
            return tuple(obj)
        if isinstance(obj, sqlite3.Cursor):
            return list(obj)
        if isinstance(obj, bytes):
            # Does it encode to utf8?
            try:
                return obj.decode("utf8")
            except UnicodeDecodeError:
                return {
                    "$base64": True,
                    "encoded": base64.b64encode(obj).decode("latin1"),
                }
        return json.JSONEncoder.default(self, obj) 
Example 37
Project: DDEA-DEV   Author: TinyOS-Camp   File: json_util.py    GNU General Public License v2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return json.JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)} 
Example 38
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: font_manager.py    MIT License 5 votes vote down vote up
def json_dump(data, filename):
    """
    Dumps a data structure as JSON in the named file.

    Handles FontManager and its fields.  File paths that are children of the
    Matplotlib data path (typically, fonts shipped with Matplotlib) are stored
    relative to that data path (to remain valid across virtualenvs).
    """
    with open(filename, 'w') as fh:
        try:
            json.dump(data, fh, cls=JSONEncoder, indent=2)
        except OSError as e:
            _log.warning('Could not save font_manager cache {}'.format(e)) 
Example 39
Project: opadmin   Author: cc0411   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def encode(self, obj):
        if isinstance(obj, float):
            return format(obj, '.6f')
        return json.JSONEncoder.encode(self, obj) 
Example 40
Project: opadmin   Author: cc0411   File: views.py    GNU General Public License v3.0 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 41
Project: ANALYSE-v1   Author: analyseuc3m   File: encoder.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def default(self, obj):  # pylint: disable=method-hidden
        if isinstance(obj, (CourseDetails, CourseGradingModel)):
            return obj.__dict__
        elif isinstance(obj, Location):
            return obj.dict()
        elif isinstance(obj, datetime.datetime):
            return Date().to_json(obj)
        else:
            return JSONEncoder.default(self, obj) 
Example 42
Project: IntercomBot   Author: IndicoDataSolutions   File: handler.py    MIT License 5 votes vote down vote up
def default(self, o):
        return json.JSONEncoder.default(self, o) 
Example 43
Project: IntercomBot   Author: IndicoDataSolutions   File: handler.py    MIT License 5 votes vote down vote up
def respond(self, data, code=200):
        self.set_status(code)
        self.write(JSONEncoder().encode({
            "status": code,
            "data": data
        }))
        self.finish() 
Example 44
Project: knack   Author: microsoft   File: output.py    MIT License 5 votes vote down vote up
def default(self, o):  # pylint: disable=method-hidden
        if isinstance(o, bytes) and not isinstance(o, str):
            return o.decode()
        return json.JSONEncoder.default(self, o) 
Example 45
Project: py   Author: stencila   File: host_http_server.py    Apache License 2.0 5 votes vote down vote up
def to_json(object):
    return JSONEncoder().encode(object) 
Example 46
Project: pyramid-hypernova   Author: Yelp   File: batch.py    MIT License 5 votes vote down vote up
def __init__(self, batch_url, plugin_controller, pyramid_request, max_batch_size=None, json_encoder=JSONEncoder()):
        self.batch_url = batch_url
        self.jobs = {}
        self.plugin_controller = plugin_controller
        self.max_batch_size = max_batch_size
        self.json_encoder = json_encoder
        self.pyramid_request = pyramid_request 
Example 47
Project: pyramid-hypernova   Author: Yelp   File: rendering_test.py    MIT License 5 votes vote down vote up
def test_encode():
    data = {
        'foo': '<script>alert(0);</script>',
    }
    assert encode(data, JSONEncoder()) == '{"foo": "<script&gt;alert(0);</script&gt;"}' 
Example 48
Project: pyramid-hypernova   Author: Yelp   File: rendering_test.py    MIT License 5 votes vote down vote up
def test_render_blank_markup():
    job = Job('MyCoolComponent.js', data={'title': 'sup'}, context={})
    markup = render_blank_markup('my-unique-token', job, False, JSONEncoder())

    assert markup == dedent('''
        <div data-hypernova-key="MyCoolComponentjs" data-hypernova-id="my-unique-token"></div>
        <script
          type="application/json"
          data-hypernova-key="MyCoolComponentjs"
          data-hypernova-id="my-unique-token"
        ><!--{"title": "sup"}--></script>
    ''') 
Example 49
Project: pyramid-hypernova   Author: Yelp   File: rendering_test.py    MIT License 5 votes vote down vote up
def test_render_blank_markup_with_error():
    job = Job('MyCoolComponent.js', data={'title': 'sup'}, context={})
    markup = render_blank_markup('my-unique-token', job, True, JSONEncoder())

    assert markup == dedent('''
        <div data-hypernova-key="MyCoolComponentjs" data-hypernova-id="my-unique-token"></div>
        <script
          type="application/json"
          data-hypernova-key="MyCoolComponentjs"
          data-hypernova-id="my-unique-token"
        ><!--{"title": "sup"}--></script>

        <script type="text/javascript">
            (function () {
                function ServerSideRenderingError(component) {
                    this.name = 'ServerSideRenderingError';
                    this.component = component;
                }

                ServerSideRenderingError.prototype = Object.create(ServerSideRenderingError.prototype);
                ServerSideRenderingError.prototype.constructor = ServerSideRenderingError;

                throw new ServerSideRenderingError('MyCoolComponentjs failed to render server-side, and fell back to client-side rendering.');
            }());
        </script>
    ''')  # noqa: ignore=E501 
Example 50
Project: pyramid-hypernova   Author: Yelp   File: request_test.py    MIT License 5 votes vote down vote up
def test_erroneous_send_synchronous(self, mock_fido_fetch, mock_requests_post):
        mock_requests_post.return_value.raise_for_status.side_effect = HTTPError('ayy lmao')

        query = HypernovaQuery(TEST_JOB_GROUP, 'google.com', JSONEncoder(), True, {})
        query.send()

        mock_fido_fetch.assert_not_called()
        mock_requests_post.assert_called_once()

        with pytest.raises(HypernovaQueryError) as exc_info:
            query.json()
        assert str(exc_info.value) == str(HypernovaQueryError(NetworkError('ayy lmao'))) 
Example 51
Project: pyramid-hypernova   Author: Yelp   File: request_test.py    MIT License 5 votes vote down vote up
def test_erroneous_send_asynchronous(self, mock_fido_fetch, mock_requests_post):
        mock_fido_fetch.return_value.wait.side_effect = NetworkError('ayy lmao')

        query = HypernovaQuery(TEST_JOB_GROUP, 'google.com', JSONEncoder(), False, {})
        query.send()

        mock_fido_fetch.assert_called_once()
        mock_requests_post.assert_not_called()

        with pytest.raises(HypernovaQueryError) as exc_info:
            query.json()
        assert str(exc_info.value) == str(HypernovaQueryError(NetworkError('ayy lmao'))) 
Example 52
Project: pyramid-hypernova   Author: Yelp   File: batch_test.py    MIT License 5 votes vote down vote up
def batch_request(spy_plugin_controller, test_data, request):
    json_encoder = ComplexJSONEncoder() if test_data[1] else JSONEncoder()
    return BatchRequest(
        'http://localhost:8888',
        spy_plugin_controller,
        pyramid_request=pyramid.request.Request.blank('/'),
        max_batch_size=request.param,
        json_encoder=json_encoder,
    ) 
Example 53
Project: viewer-demo   Author: CCI-Tools   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, numpy.ndarray):
            if obj.ndim == 1:
                return obj.tolist()
            else:
                return [self.default(obj[i]) for i in range(obj.shape[0])]
        return json.JSONEncoder.default(self, obj) 
Example 54
Project: python-protolite   Author: thelinuxkid   File: generator.py    MIT License 5 votes vote down vote up
def iterencode(self, obj, prefixes):
        data = json.JSONEncoder.iterencode(self, obj)
        for value in data:
            value = underscore(value, prefixes=prefixes)
            stripped = value.strip('"')
            if stripped.isdigit():
                value = stripped
            yield value 
Example 55
Project: erede-python   Author: DevelopersRede   File: RedeSerializable.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, 'serialize'):
            return obj.serialize()
        else:
            return json.JSONEncoder.default(self, obj) 
Example 56
Project: bbq   Author: ocadotechnology   File: request_encoder.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, 'to_json'):
            return obj.to_json()
        else:
            return json.JSONEncoder.default(self, obj) 
Example 57
Project: katana-sdk-python2   Author: kusanagi   File: json.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            # Note: Use str instead of float
            # to avoid dealing with presition
            return str(obj)
        elif isinstance(obj, datetime.datetime):
            return utils.date_to_str(obj)
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif hasattr(obj, '__serialize__'):
            return obj.__serialize__()
        elif isinstance(obj, bytes):
            return obj.decode('utf8')

        return json.JSONEncoder.default(self, obj) 
Example 58
Project: python-wifi-survey-heatmap   Author: jantman   File: ui.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, type(b'')):
            return obj.decode()
        return json.JSONEncoder.default(self, obj) 
Example 59
Project: prom_notify   Author: liveonnet   File: tools_lib.py    Apache License 2.0 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 60
Project: eventsourcing   Author: johnbywater   File: hashing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hash_object(json_encoder: JSONEncoder, obj: dict) -> str:
    """
    Calculates SHA-256 hash of JSON encoded 'obj'.

    :param json_encoder: JSON encoder object.
    :param obj: Object to be hashed.
    :return: SHA-256 as hexadecimal string.
    :rtype str
    """
    s = json_encoder.encode((obj, SALT_FOR_DATA_INTEGRITY))
    return hashlib.sha256(s.encode()).hexdigest() 
Example 61
Project: eventsourcing   Author: johnbywater   File: factory.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def construct_sqlalchemy_eventstore(
    session: Any,
    sequenced_item_class: Optional[Type[NamedTuple]] = None,
    sequence_id_attr_name: Optional[str] = None,
    position_attr_name: Optional[str] = None,
    json_encoder_class: Optional[Type[JSONEncoder]] = None,
    json_decoder_class: Optional[Type[JSONDecoder]] = None,
    cipher: Optional[AESCipher] = None,
    record_class: Optional[type] = None,
    contiguous_record_ids: bool = False,
    application_name: Optional[str] = None,
    pipeline_id: int = DEFAULT_PIPELINE_ID,
) -> EventStore:
    sequenced_item_class = sequenced_item_class or StoredEvent  # type: ignore
    sequenced_item_mapper = SequencedItemMapper[DomainEvent](
        sequenced_item_class=sequenced_item_class,
        sequence_id_attr_name=sequence_id_attr_name,
        position_attr_name=position_attr_name,
        json_encoder_class=json_encoder_class,
        json_decoder_class=json_decoder_class,
        cipher=cipher,
    )
    factory = SQLAlchemyInfrastructureFactory(
        session=session,
        integer_sequenced_record_class=record_class or StoredEventRecord,
        sequenced_item_class=sequenced_item_class,
        contiguous_record_ids=contiguous_record_ids,
        application_name=application_name,
        pipeline_id=pipeline_id,
    )
    record_manager = factory.construct_integer_sequenced_record_manager()
    event_store = EventStore[DomainEvent, AbstractRecordManager](
        record_manager=record_manager, event_mapper=sequenced_item_mapper
    )
    return event_store 
Example 62
Project: eventsourcing   Author: johnbywater   File: sequenceditemmapper.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self,
        sequenced_item_class: Optional[Type[NamedTuple]] = None,
        sequence_id_attr_name: Optional[str] = None,
        position_attr_name: Optional[str] = None,
        json_encoder_class: Optional[Type[JSONEncoder]] = None,
        json_decoder_class: Optional[Type[JSONDecoder]] = None,
        cipher: Optional[AESCipher] = None,
        compressor: Any = None,
        other_attr_names: Tuple[str, ...] = (),
    ):
        if sequenced_item_class is not None:
            self.sequenced_item_class = sequenced_item_class
        else:
            self.sequenced_item_class = SequencedItem  # type: ignore
        self.json_encoder_class = json_encoder_class or ObjectJSONEncoder
        self.json_encoder = self.json_encoder_class(
            separators=JSON_SEPARATORS, sort_keys=True
        )
        self.json_decoder_class = json_decoder_class or ObjectJSONDecoder
        self.json_decoder = self.json_decoder_class()
        self.cipher = cipher
        self.compressor = compressor
        self.field_names = SequencedItemFieldNames(self.sequenced_item_class)
        self.sequence_id_attr_name = (
            sequence_id_attr_name or self.field_names.sequence_id
        )
        self.position_attr_name = position_attr_name or self.field_names.position
        self.other_attr_names = other_attr_names or self.field_names.other_names 
Example 63
Project: eventsourcing   Author: johnbywater   File: factory.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self,
        record_manager_class: Optional[Type[AbstractRecordManager]] = None,
        sequenced_item_class: Optional[Type[NamedTuple]] = None,
        event_store_class: Optional[Type[AbstractEventStore]] = None,
        sequenced_item_mapper_class: Optional[Type[AbstractSequencedItemMapper]] = None,
        json_encoder_class: Optional[Type[JSONEncoder]] = None,
        json_decoder_class: Optional[Type[JSONDecoder]] = None,
        integer_sequenced_record_class: Optional[type] = None,
        timestamp_sequenced_record_class: Optional[type] = None,
        snapshot_record_class: Optional[type] = None,
        contiguous_record_ids: bool = False,
        application_name: Optional[str] = None,
        pipeline_id: int = DEFAULT_PIPELINE_ID,
    ):
        self.record_manager_class = (
            record_manager_class or type(self).record_manager_class
        )
        self.event_store_class = event_store_class or type(self).event_store_class
        self.sequenced_item_class = (
            sequenced_item_class or type(self).sequenced_item_class
        )
        self.sequenced_item_mapper_class = (
            sequenced_item_mapper_class or type(self).sequenced_item_mapper_class
        )
        self.json_encoder_class = json_encoder_class or type(self).json_encoder_class
        self.json_decoder_class = json_decoder_class or type(self).json_decoder_class

        self._integer_sequenced_record_class = integer_sequenced_record_class

        self._timestamp_sequenced_record_class = timestamp_sequenced_record_class

        self._snapshot_record_class = snapshot_record_class

        self.contiguous_record_ids = contiguous_record_ids
        self.application_name = application_name
        self.pipeline_id = pipeline_id 
Example 64
Project: ludwig   Author: uber   File: data_utils.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        elif isinstance(obj, tuple):
            return list(obj)
        elif isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return json.JSONEncoder.default(self, obj) 
Example 65
Project: Hierarchical-Meta-Reinforcement-Learning   Author: navneet-nmk   File: logging.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, type):
            return {'$class': o.__module__ + "." + o.__name__}
        elif isinstance(o, Enum):
            return {
                '$enum': o.__module__ + "." + o.__class__.__name__ + '.' + o.name
            }
        elif callable(o):
            return {
                '$function': o.__module__ + "." + o.__name__
            }
        return json.JSONEncoder.default(self, o) 
Example 66
Project: neo4j-social-network   Author: bestvibes   File: jsonencoder.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (datetime, date, time)):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return str(obj)
        if isinstance(obj, (set, frozenset)):
            return list(obj)
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj) 
Example 67
Project: neo4j-social-network   Author: bestvibes   File: jsonencoder.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (datetime, date, time)):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return str(obj)
        if isinstance(obj, (set, frozenset)):
            return list(obj)
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj) 
Example 68
Project: neo4j-social-network   Author: bestvibes   File: jsonencoder.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (datetime, date, time)):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return str(obj)
        if isinstance(obj, (set, frozenset)):
            return list(obj)
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj) 
Example 69
Project: neo4j-social-network   Author: bestvibes   File: jsonencoder.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (datetime, date, time)):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return str(obj)
        if isinstance(obj, (set, frozenset)):
            return list(obj)
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj) 
Example 70
Project: AutoLeague   Author: DomNomNom   File: skill_pool.py    MIT License 5 votes vote down vote up
def default(self, obj):
        for cls, tag in known_types.items():
            if not isinstance(obj, cls):
                continue
            json_obj = obj.__dict__.copy()
            if isinstance(obj, TrueSkill):
                del json_obj['cdf']
                del json_obj['pdf']
                del json_obj['ppf']
            json_obj[tag] = True
            return json_obj
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

# ====== JSON -> SkillPool ====== 
Example 71
Project: FARM   Author: deepset-ai   File: inference_rest_api.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, np.float32):
            return str(obj)
        return json.JSONEncoder.default(self, obj) 
Example 72
Project: AI-Tweet-Validator   Author: JoshuaGRubin   File: evaluate_model.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj) 
Example 73
Project: parselglossy   Author: dev-cafe   File: utils.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, complex):
            return {"__complex__": [obj.real, obj.imag]}
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj) 
Example 74
Project: rucio   Author: rucio   File: utils.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):  # pylint: disable=E0202
        if isinstance(obj, datetime.datetime):
            # convert any datetime to RFC 1123 format
            return date_to_str(obj)
        elif isinstance(obj, (datetime.time, datetime.date)):
            # should not happen since the only supported date-like format
            # supported at dmain schema level is 'datetime' .
            return obj.isoformat()
        elif isinstance(obj, datetime.timedelta):
            return obj.days * 24 * 60 * 60 + obj.seconds
        elif isinstance(obj, EnumSymbol):
            return obj.description
        elif isinstance(obj, (InternalAccount, InternalScope)):
            return obj.external
        return json.JSONEncoder.default(self, obj) 
Example 75
Project: pyDcop   Author: Orange-OpenSource   File: orchestrator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, np.int64):
            return int(obj)
        return json.JSONEncoder.default(self, obj) 
Example 76
Project: pyDcop   Author: Orange-OpenSource   File: solve.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, np.int64):
            return int(obj)
        return json.JSONEncoder.default(self, obj) 
Example 77
Project: pyDcop   Author: Orange-OpenSource   File: run.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, np.int64):
            return int(obj)
        return json.JSONEncoder.default(self, obj) 
Example 78
Project: Tattle   Author: nickmaccarthy   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj) 
Example 79
Project: pycons3rt   Author: cons3rt   File: slack.py    GNU General Public License v3.0 4 votes vote down vote up
def send(self):
        """Sends the Slack message

        This public method sends the Slack message along with any
        attachments, then clears the attachments array.

        :return: None
        :raises: OSError
        """
        log = logging.getLogger(self.cls_logger + '.send')

        if self.attachments:
            self.payload['attachments'] = self.attachments

        # Encode payload in JSON
        log.debug('Using payload: %s', self.payload)
        try:
            json_payload = json.JSONEncoder().encode(self.payload)
        except(TypeError, ValueError, OverflowError):
            _, ex, trace = sys.exc_info()
            msg = 'There was a problem encoding the JSON payload\n{e}'.format(e=str(ex))
            raise OSError, msg, trace
        else:
            log.debug('JSON payload: %s', json_payload)

        # Post to Slack!
        log.debug('Posting message to Slack...')
        try:
            result = requests.post(url=self.webhook_url, data=json_payload)
        except requests.exceptions.ConnectionError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem posting to Slack\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise OSError, msg, trace

        # Check return code
        if result.status_code != 200:
            log.error('Slack post to url {u} failed with code: {c}'.format(c=result.status_code, u=self.webhook_url))
        else:
            log.debug('Posted message to Slack successfully.')

        # Clear out attachments after sending
        self.attachments = []
        self.payload.pop('attachments', None) 
Example 80
Project: autopyfactory   Author: PanDAWMS   File: APFMonitorOldPlugin.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, apfqueue, monitor_id):
        '''
        apfqueue is a reference to the APFQueue object creating this plugin.

        monitor_id is the value for id_var (input of the singletonfactory)
        to decide if a new object has to be really created or not.
        It is the name of the section [] in monitor config object
        
        Also sends initial ping to monitor server. 
        
        '''
        self.log = logging.getLogger('main.monitor [singleton created by %s with id %s]' %(apfqueue.apfqname, monitor_id))
        mainlevel = logging.getLogger('main').getEffectiveLevel()
        self.log.setLevel(mainlevel)
        self.log.debug("Start...")


        self.apfqname = apfqueue.apfqname
        self.qcl = apfqueue.factory.qcl
        self.fcl = apfqueue.factory.fcl
        self.mcl = apfqueue.factory.mcl
    
        self.fid = self.fcl.generic_get('Factory','factoryId')
        self.version = self.fcl.generic_get('Factory', 'versionTag')
        self.email = self.fcl.generic_get('Factory','factoryAdminEmail')
        self.owner = self.email
        self.baselogurl = self.fcl.generic_get('Factory','baseLogDirUrl')

        self.monurl = self.mcl.generic_get(monitor_id, 'monitorURL')
        self.crurl = self.monurl + 'c/'
        self.msgurl = self.monurl + 'm/'
        self.furl = self.monurl + 'h/'
        
        self.crlist = []
        self.msglist = []
        
        self.jsonencoder = json.JSONEncoder()
        self.buffer = StringIO.StringIO()
        
        self.log.debug('Instantiated monitor')
        self.registerFactory()     
        self.log.debug('Done.')