Python simplejson.JSONEncoder() Examples

The following are code examples for showing how to use simplejson.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: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def default(self, obj):
                # convert all iterables to lists
        if hasattr(obj, '__iter__'):
            return list(obj)
        # convert cursors to lists
        elif isinstance(obj, pymongo.cursor.Cursor):
            return list(obj)
        # convert ObjectId to string
        elif isinstance(obj, pymongo.objectid.ObjectId):
            return unicode(obj)
        # dereference DBRef
        elif isinstance(obj, pymongo.dbref.DBRef):
            return db.dereference(obj)
        # convert dates to strings
        elif isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date) or isinstance(obj, datetime.time):
            return unicode(obj)
        return simplejson.JSONEncoder.default(self, obj) 
Example 2
Project: kingpin   Author: pinterest   File: managed_datastructures.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, list_domain, list_key, list_name, list_description,
                 zk_hosts, aws_keyfile, s3_bucket, s3_endpoint="s3.amazonaws.com",
                 encoder_cls=json.JSONEncoder, decoder_cls=json.JSONDecoder,
                 update_callback=None, force_config_update=None):

        kwargs = {}
        if force_config_update is not None:
            kwargs['force_config_update'] = force_config_update

        super(ManagedJsonSerializableDataConfig, self).__init__(
            list_domain, list_key, list_name, list_description, zk_hosts,
            aws_keyfile, s3_bucket, s3_endpoint=s3_endpoint, **kwargs)

        self.encoder_cls = encoder_cls
        self.decoder_cls = decoder_cls
        self.update_callback = None
        if update_callback:
            self.set_update_callback(update_callback) 
Example 3
Project: anillo   Author: jespino   File: json.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
    """
    A middleware that parses the body of json requests and
    encodes the json responses.

    NOTE: this middleware exists just for backward compatibility,
    but it has some limitations in terms of response body encoding
    because it only accept list or dictionary outputs and json
    specification allows store other values also.

    It is recommended use the `wrap_json_body` and wrap_json_response`
    instead of this.
    """

    if func is None:
        return functools.partial(
            wrap_json,
            encoder=encoder,
            preserve_raw_body=preserve_raw_body
        )

    wrapped_func = wrap_json_body(func, preserve_raw_body=preserve_raw_body)
    wrapped_func = wrap_json_response(wrapped_func, encoder=encoder)
    return wrapped_func 
Example 4
Project: anillo   Author: jespino   File: json.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def wrap_json_response(func=None, *, encoder=json.JSONEncoder):
    """
    A middleware that encodes in json the response body in case
    of that the "Content-Type" header is "application/json".

    This middlware accepts and optional `encoder` parameter, that
    allow to the user specify its own json encoder class.
    """

    if func is None:
        return functools.partial(wrap_json_response, encoder=encoder)

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if "Content-Type" in response.headers and response.headers['Content-Type'] is not None:
            ctype, pdict = parse_header(response.headers.get('Content-Type', ''))
            if ctype == "application/json" and (isinstance(response.body, dict) or isinstance(response.body, list)):
                response.body = json.dumps(response.body, cls=encoder)
        return response

    return wrapper 
Example 5
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 6
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj, **kwargs):

        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%dT%H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, ObjectId):
            return str(obj)
        elif isinstance(obj, DBRef):
            return {'collection': obj.collection,
                    'id': str(obj.id),
                    'database': obj.database}
        return simplejson.JSONEncoder.default(obj, **kwargs) 
Example 7
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    """Tests the input object, obj, to encode as JSON."""

    if hasattr(obj, 'to_dict'):
      return getattr(obj, 'to_dict')()

    if isinstance(obj, query.Query):
      return list(obj)

    elif isinstance(obj, datetime.datetime):
      return obj.isoformat()

    elif isinstance(obj, time.struct_time):
      return list(obj)

    elif isinstance(obj, users.User):
      output = {}
      methods = ['nickname', 'email', 'auth_domain']
      for method in methods:
        output[method] = getattr(obj, method)()
      return output

    elif isinstance(obj, model.Key):
      return obj.get()

    return simplejson.JSONEncoder.default(self, obj) 
Example 8
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_unicode.py    MIT License 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 9
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_recursion.py    MIT License 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 10
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_iterable.py    MIT License 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 11
Project: lambda-chef-node-cleanup   Author: awslabs   File: json.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, 'to_dict'):
            return maybe_call(obj.to_dict)
        elif hasattr(obj, 'to_list'):
            return maybe_call(obj.to_list)
        elif isinstance(obj, types.GeneratorType):
            return list(obj)
        return super(JSONEncoder, self).default(obj) 
Example 12
Project: tra-tracking-on-gae   Author: elliot79313   File: test_unicode.py    MIT License 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 13
Project: tra-tracking-on-gae   Author: elliot79313   File: test_recursion.py    MIT License 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 14
Project: KALanguageReport   Author: alani1   File: gviz_api.py    MIT License 5 votes vote down vote up
def __init__(self):
    json.JSONEncoder.__init__(self,
                              separators=(",", ":"),
                              ensure_ascii=False) 
Example 15
Project: KALanguageReport   Author: alani1   File: _gviz_api.py    MIT License 5 votes vote down vote up
def __init__(self):
    json.JSONEncoder.__init__(self,
                              separators=(",", ":"),
                              ensure_ascii=False) 
Example 16
Project: ableton-live-webapi   Author: valsteen   File: test_unicode.py    The Unlicense 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 17
Project: ableton-live-webapi   Author: valsteen   File: test_recursion.py    The Unlicense 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 18
Project: ableton-live-webapi   Author: valsteen   File: test_iterable.py    The Unlicense 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 19
Project: metatlas   Author: biorack   File: handle_service.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        if isinstance(obj, frozenset):
            return list(obj)
        return json.JSONEncoder.default(self, obj) 
Example 20
Project: pycopia   Author: kdart   File: json.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
    super(JSONEncoder, self).__init__(ensure_ascii=False, encoding="utf-8")
    self._registry = {} 
Example 21
Project: pycopia   Author: kdart   File: json.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    for checker, simplifier in self._registry.itervalues():
      if checker(obj):
        return simplifier(obj)
    return super(JSONEncoder, self).default(obj)

#  def encode(self, obj):
#    for checker, simplifier in self._registry.itervalues():
#      if checker(obj):
#        return super(JSONEncoder, self).encode(simplifier(obj))
#    return super(JSONEncoder, self).encode(obj) 
Example 22
Project: pycopia   Author: kdart   File: json.py    Apache License 2.0 5 votes vote down vote up
def GetJSONEncoder():
    # encoding: native -> JSON
  global _ENCODER
  if _ENCODER is None:
    _ENCODER = JSONEncoder()
    _ENCODER.register("datetime", _DtChecker, _DtSimplifier)
    _ENCODER.register("date", _DateChecker, _DateSimplifier)
    _ENCODER.register("set", _set_checker, _set_simplifier)
    _ENCODER.register("enums", _enum_checker, _enum_simplifier)
  return _ENCODER 
Example 23
Project: devops   Author: cc0411   File: interactive.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 24
Project: fund   Author: Frank-qlu   File: test_unicode.py    Apache License 2.0 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 25
Project: fund   Author: Frank-qlu   File: test_recursion.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 26
Project: fund   Author: Frank-qlu   File: test_iterable.py    Apache License 2.0 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 27
Project: kael   Author: 360skyeye   File: common.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')
        elif isinstance(obj, ObjectId):
            return str(obj)
        return json.JSONEncoder.default(self, obj) 
Example 28
Project: UnitX   Author: supertask   File: prettyprint.py    MIT License 5 votes vote down vote up
def default(self, o):
        try:
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)
        
        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            return str(o) 
Example 29
Project: UnitX   Author: supertask   File: prettyprint.py    MIT License 5 votes vote down vote up
def default(self, o):
        try:
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)
        
        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            return str(o) 
Example 30
Project: hawkular-client-python   Author: hawkular   File: client.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, ApiObject):
            return obj.to_json_object()
        else:
            return json.JSONEncoder.default(self, obj) 
Example 31
Project: ml-fairness-gym   Author: google   File: core.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    # First check if the object has a to_jsonable() method which converts it to
    # a representation that can be json encoded.
    try:
      return obj.to_jsonable()
    except AttributeError:
      pass

    if callable(obj):
      return {'callable': obj.__name__}

    if isinstance(obj, (bool, np.bool_)):
      return int(obj)

    if isinstance(obj, enum.Enum):
      return {'__enum__': str(obj)}

    if isinstance(obj, np.ndarray):
      return obj.tolist()
    if isinstance(obj, (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)
    if isinstance(obj, (bool, np.bool_)):
      return str(obj)
    if isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
      return float(obj)
    if isinstance(obj, nx.Graph):
      return nx.readwrite.json_graph.node_link_data(obj)
    if isinstance(obj, np.random.RandomState):
      state = obj.get_state()
      return {
          RANDOM_STATE_KEY:
              (state[0], state[1].tolist(), state[2], state[3], state[4])
      }
    if isinstance(obj, Params) or isinstance(obj, State):
      return obj.asdict()
    return json.JSONEncoder.default(self, obj) 
Example 32
Project: oscars2016   Author: 0x0ece   File: test_unicode.py    Apache License 2.0 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 33
Project: oscars2016   Author: 0x0ece   File: test_recursion.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 34
Project: oscars2016   Author: 0x0ece   File: test_iterable.py    Apache License 2.0 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 35
Project: pxf   Author: greenplum-db   File: test_unicode.py    Apache License 2.0 5 votes vote down vote up
def test_encoding1():
    encoder = S.JSONEncoder(encoding='utf-8')
    u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    s = u.encode('utf-8')
    ju = encoder.encode(u)
    js = encoder.encode(s)
    assert ju == js 
Example 36
Project: pxf   Author: greenplum-db   File: test_recursion.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if o is TestObject:
            if self.recurse:
                return [TestObject]
            else:
                return 'TestObject'
        simplejson.JSONEncoder.default(o) 
Example 37
Project: that-startpage-rocks   Author: the-duck   File: test_unicode.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 38
Project: that-startpage-rocks   Author: the-duck   File: test_recursion.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 39
Project: that-startpage-rocks   Author: the-duck   File: test_iterable.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 40
Project: appkernel   Author: accelero-cloud   File: engine.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        try:
            return default_json_serializer(obj)
        except TypeError:
            pass
        return json.JSONEncoder.default(self, obj) 
Example 41
Project: cohesive-networks-vns3-vpn-monitoring   Author: trek10inc   File: test_unicode.py    MIT License 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 42
Project: cohesive-networks-vns3-vpn-monitoring   Author: trek10inc   File: test_recursion.py    MIT License 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 43
Project: cohesive-networks-vns3-vpn-monitoring   Author: trek10inc   File: test_iterable.py    MIT License 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 44
Project: CENTAUR   Author: susantoj   File: globals.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        """Default is called by JSONEncoder for serialisation of data.
           Passes back to core default method if not Numpy data."""
        if isinstance(obj, np.complex):
            return dict(__npcomplex__=True, real=obj.real, imag=obj.imag)            
        if isinstance(obj, np.ndarray):
            return dict(__nparray__=True, data=obj.tolist())
        return json.JSONEncoder.default(self, obj) 
Example 45
Project: GoogleAi   Author: nattimmis   File: utils.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    if isinstance(obj, (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 isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
      return float(obj)
    elif isinstance(obj, np.ndarray):
      return obj.tolist()
    return simplejson.JSONEncoder.default(self, obj) 
Example 46
Project: GoogleAi   Author: nattimmis   File: logistic_reg_pystan.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    if isinstance(obj, (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 isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
      return float(obj)
    elif isinstance(obj, np.ndarray):
      return obj.tolist()
    return simplejson.JSONEncoder.default(self, obj) 
Example 47
Project: GoogleAi   Author: nattimmis   File: logistic_reg_gamma_pystan.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    if isinstance(obj, (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 isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
      return float(obj)
    elif isinstance(obj, np.ndarray):
      return obj.tolist()
    return simplejson.JSONEncoder.default(self, obj) 
Example 48
Project: GoogleAi   Author: nattimmis   File: gp_reg_pystan.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    if isinstance(obj, (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 isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
      return float(obj)
    elif isinstance(obj, np.ndarray):
      return obj.tolist()
    return simplejson.JSONEncoder.default(self, obj) 
Example 49
Project: disentanglement_lib   Author: google-research   File: results.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
    if isinstance(obj, (np.float_, np.float32, np.float16, np.float64)):
      return float(obj)
    elif isinstance(obj,
                    (np.intc, np.intp, np.int_, np.int8, np.int16, np.int32,
                     np.int64, np.uint8, np.uint16, np.uint32, np.uint64)):
      return int(obj)
    elif isinstance(obj, np.ndarray):
      obj = obj.tolist()
    return json.JSONEncoder.default(self, obj) 
Example 50
Project: alfredToday   Author: jeeftor   File: test_unicode.py    MIT License 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 51
Project: alfredToday   Author: jeeftor   File: test_recursion.py    MIT License 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 52
Project: alfredToday   Author: jeeftor   File: test_iterable.py    MIT License 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 53
Project: PocHunter   Author: DavexPro   File: dotted.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, DottedCollection):
            return obj.store
        else:
            return json.JSONEncoder.default(obj) 
Example 54
Project: old-dotfiles   Author: hawkw   File: test_unicode.py    MIT License 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 55
Project: old-dotfiles   Author: hawkw   File: test_recursion.py    MIT License 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 56
Project: pureapp   Author: samisalkosuo   File: test_unicode.py    Apache License 2.0 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 57
Project: pureapp   Author: samisalkosuo   File: test_recursion.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 58
Project: pureapp   Author: samisalkosuo   File: test_unicode.py    Apache License 2.0 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 59
Project: pureapp   Author: samisalkosuo   File: test_recursion.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 60
Project: health-mosconi   Author: GNUHealth-Mosconi   File: jsonrpc.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(JSONEncoder, self).__init__(*args, **kwargs)
        # Force to use our custom decimal with simplejson
        self.use_decimal = False 
Example 61
Project: health-mosconi   Author: GNUHealth-Mosconi   File: jsonrpc.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        marshaller = self.serializers.get(type(obj),
            super(JSONEncoder, self).default)
        return marshaller(obj) 
Example 62
Project: ra   Author: ramses-tech   File: dsl.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, raml_path_or_string, app='config:test.ini',
                 relative_to=None, JSONEncoder=None):
        """Instantiates an API test suite for the given :raml: and :app:."""

        if relative_to is None:
            relative_to = guess_rootdir()

        if isinstance(app, webtest.TestApp):
            app = app
        else:
            app = webtest.TestApp(app, relative_to=relative_to)
        self.app = app

        if not raml.is_raml(raml_path_or_string):
            raml_path_or_string = os.path.normpath(
                os.path.join(relative_to, raml_path_or_string))

        self.raml_path, self.raml = _parse_raml(raml_path_or_string)
        self.path_prefix = path_from_uri(self.raml.base_uri)
        self.resource_scopes = []

        self.test_suite = TestSuite()

        self.RequestClass = make_request_class(app)

        self.JSONEncoder = JSONEncoder or json.JSONEncoder

        self.examples = self._define_factories() 
Example 63
Project: teambition-api   Author: jxtech   File: utils.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.date):
            encoded = obj.isoformat()
        elif isinstance(obj, datetime.datetime):
            encoded = obj.isoformat()
        else:
            encoded = super(JSONEncoder, self).default(obj)
        return encoded 
Example 64
Project: syntheticmass   Author: synthetichealth   File: test_unicode.py    Apache License 2.0 5 votes vote down vote up
def test_encoding1(self):
        encoder = json.JSONEncoder(encoding='utf-8')
        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
        s = u.encode('utf-8')
        ju = encoder.encode(u)
        js = encoder.encode(s)
        self.assertEqual(ju, js) 
Example 65
Project: syntheticmass   Author: synthetichealth   File: test_recursion.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if o is JSONTestObject:
            if self.recurse:
                return [JSONTestObject]
            else:
                return 'JSONTestObject'
        return json.JSONEncoder.default(o) 
Example 66
Project: syntheticmass   Author: synthetichealth   File: test_iterable.py    Apache License 2.0 5 votes vote down vote up
def iter_dumps(obj, **kw):
    return ''.join(json.JSONEncoder(**kw).iterencode(obj)) 
Example 67
Project: python-igraph   Author: igraph   File: gephi.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, encoder=None):
        """Constructs a Gephi graph streamer that will post graphs to a
        given file-like object or a Gephi connection.

        `encoder` must either be ``None`` or an instance of ``json.JSONEncoder``
        and it must contain the JSON encoder to be used when posting JSON objects.
        """
        self.encoder = encoder or json.JSONEncoder(ensure_ascii=True)
        self.format = GephiGraphStreamingAPIFormat() 
Example 68
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.') 
Example 69
Project: fleaker   Author: croscon   File: json.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def default(self, obj):
        """Encode individual objects into their JSON representation.

        This method is used by :class:`flask.json.JSONEncoder` to encode
        individual items in the JSON object.

        Args:
            obj (object): Any Python object we wish to convert to JSON.

        Returns:
            str: The stringified, valid JSON representation of our provided
                object.
        """
        if isinstance(obj, decimal.Decimal):
            obj = format(obj, 'f')
            str_digit = text_type(obj)

            return (str_digit.rstrip('0').rstrip('.')
                    if '.' in str_digit
                    else str_digit)

        elif isinstance(obj, phonenumbers.PhoneNumber):
            return phonenumbers.format_number(
                obj,
                phonenumbers.PhoneNumberFormat.E164
            )

        elif isinstance(obj, pendulum.Pendulum):
            return text_type(obj)

        elif isinstance(obj, arrow.Arrow):
            return text_type(obj)

        elif isinstance(obj, (datetime.datetime, datetime.date)):
            return obj.isoformat()

        try:
            return list(iter(obj))
        except TypeError:
            pass

        return super(FleakerJSONEncoder, self).default(obj)