ask/carrot · serialization.py
python logo
def register_json():
    """Register a encoder/decoder for JSON serialization."""
    from anyjson import serialize as json_serialize
    from anyjson import deserialize as json_deserialize

    registry.register('json', json_serialize, json_deserialize,
                      content_type='application/json',
                      content_encoding='utf-8')
Similar code snippets
1.
insightindustry/validator-collection · checkers.py
Match rating: 57.16% · See similar code snippets
python logo
def is_json(value,
            schema = None,
            json_serializer = None,
            **kwargs):
    """Indicate whether ``value`` is a valid JSON object.

    .. note::

      ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
      meta-schema using a ``$schema`` property, the schema will be assumed to conform to
      Draft 7.

    :param value: The value to evaluate.

    :param schema: An optional JSON schema against which ``value`` will be validated.
    :type schema: :class:`dict <python:dict>` / :class:`str <python:str>` /
      :obj:`None <python:None>`

    :returns: ``True`` if ``value`` is valid, ``False`` if it is not.
    :rtype: :class:`bool <python:bool>`

    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
      keyword parameters passed to the underlying validator

    """
    try:
        value = validators.json(value,
                                schema = schema,
                                json_serializer = json_serializer,
                                **kwargs)
    except SyntaxError as error:
        raise error
    except Exception:
        return False

    return True
2.
croach/django-simple-rest · serializers.py
Match rating: 55.38% · See similar code snippets
python logo
def to_json(content, indent=None):
    """
    Serializes a python object as JSON

    This method uses the DJangoJSONEncoder to to ensure that python objects
    such as Decimal objects are properly serialized. It can also serialize
    Django QuerySet objects.
    """
    if isinstance(content, QuerySet):
        json_serializer = serializers.get_serializer('json')()
        serialized_content = json_serializer.serialize(content, ensure_ascii=False, indent=indent)
    else:
        try:
            serialized_content = json.dumps(content, cls=DecimalEncoder, ensure_ascii=False, indent=indent)
        except TypeError:
            # Fix for Django 1.5
            serialized_content = json.dumps(content, ensure_ascii=False, indent=indent)
    return serialized_content
3.
alerta/alerta · format.py
Match rating: 53.58% · See similar code snippets
python logo
def register_custom_serializer() -> None:
    from kombu.serialization import register
    register('customjson', custom_json_dumps, json.loads,
             content_type='application/x-customjson',
             content_encoding='utf-8')
4.
Alonreznik/dynamodb-json · json_util.py
Match rating: 53.54% · See similar code snippets
python logo
def dumps(dct, as_dict=False, **kwargs):
    """ Dump the dict to json in DynamoDB Format
        You can use any other simplejson or json options
        :param dct - the dict to dump
        :param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting
        :returns: DynamoDB json format.
        """

    result_ = TypeSerializer().serialize(json.loads(json.dumps(dct, default=json_serial),
                                                    use_decimal=True))
    if as_dict:
        return next(six.iteritems(result_))[1]
    else:
        return json.dumps(next(six.iteritems(result_))[1], **kwargs)
5.
klen/adrest · templatetags.py
Match rating: 53.05% · See similar code snippets
python logo
def adrest_jsonify(content, **options):
    """ Serialize any object to JSON .

    :return str: Rendered string.

    """
    from adrest.utils.serializer import JSONSerializer
    worker = JSONSerializer(**options)
    return worker.serialize(content)
6.
wtsi-hgi/python-hgijson · _serialization.py
Match rating: 52.48% · See similar code snippets
python logo
def decode_parsed(self, parsed_json: PrimitiveJsonType) -> SerializableType:
        deserializer = self._create_deserializer()
        return deserializer.deserialize(parsed_json)
7.
bokeh/bokeh · instance.py
Match rating: 51.79% · See similar code snippets
python logo
def from_json(self, json, models=None):
        if json is None:
            return None
        elif isinstance(json, dict):
            from ...model import Model
            if issubclass(self.instance_type, Model):
                if models is None:
                    raise DeserializationError("%s can't deserialize without models" % self)
                else:
                    model = models.get(json["id"])

                    if model is not None:
                        return model
                    else:
                        raise DeserializationError("%s failed to deserialize reference to %s" % (self, json))
            else:
                attrs = {}

                for name, value in iteritems(json):
                    prop_descriptor = self.instance_type.lookup(name).property
                    attrs[name] = prop_descriptor.from_json(value, models)

                # XXX: this doesn't work when Instance(Superclass) := Subclass()
                # Serialization dict must carry type information to resolve this.
                return self.instance_type(**attrs)
        else:
            raise DeserializationError("%s expected a dict or None, got %s" % (self, json))
8.
jingming/spotify · device.py
Match rating: 50.8% · See similar code snippets
python logo
def from_json(cls, json):
        return Device(
            json['id'],
            json['is_active'],
            json['is_restricted'],
            json['name'],
            json['type'],
            json['volume_percent']
        )
9.
rgs1/zk_shell · shell.py
Match rating: 50.5% · See similar code snippets
python logo
def json_deserialize(data):
    if data is None:
        raise BadJSON()

    try:
        obj = json.loads(data)
    except ValueError:
        raise BadJSON()

    return obj
10.
howie6879/ruia · response.py
Match rating: 50.3% · See similar code snippets
python logo
async def json(self,
                   *,
                   encoding: str = None,
                   loads: JSONDecoder = DEFAULT_JSON_DECODER,
                   content_type: Optional[str] = 'application/json') -> Any:
        """Read and decodes JSON response."""
        return await self._aws_json(
            encoding=encoding, loads=loads, content_type=content_type)