当前位置: 首页>>代码示例>>Python>>正文


Python encoder.JSONEncoder类代码示例

本文整理汇总了Python中json.encoder.JSONEncoder的典型用法代码示例。如果您正苦于以下问题:Python JSONEncoder类的具体用法?Python JSONEncoder怎么用?Python JSONEncoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了JSONEncoder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: default

 def default(self, x):
     if isinstance(x, Struct):
         return dict(__JSON_Struct__=x.__json__())
     elif isinstance(x, Feature):
         return dict(__JSON_Feature__=x.__json__())
     else:
         return JSONEncoder.default(self, x)
开发者ID:icsi-berkeley,项目名称:ecg-specializer,代码行数:7,代码来源:feature.py

示例2: default

 def default(self, obj):
     if isinstance(obj, Game):
         return dict(pk = obj.pk,
                     name = obj.name,
                     password = obj.password,
                     pot_size = obj.pot_size,
                     iteration = obj.iteration,
                     start = obj.start,
                     end = obj.end,
                     state = obj.state,
                     player_count = len(obj.player_set.all()),
                     )
     elif isinstance(obj, Player):
         return dict(pk=obj.pk,
                     email=obj.email,
                     player_no=obj.player_no,
                     pair_no=obj.pair_no,
                     role=obj.role,
                     role_name=obj.get_role_display(),
                     earning=obj.earning if hasattr(obj, 'earning') else 0,
                     round=obj.round if hasattr(obj, 'round') else 0
                     )
     elif isinstance(obj, Bid):
         return dict(pk=obj.pk,
                     iteration=obj.iteration,
                     pot_size=obj.pot_size,
                     offer=obj.offer,
                     avg_offer=str(obj.avg_offer) if hasattr(obj, 'avg_offer') else '0',
                     accept=obj.accept)
     elif isinstance(obj, datetime.datetime):
         return obj.isoformat()
     return JSONEncoder.default(self, obj)
开发者ID:maowmaow,项目名称:Experiment,代码行数:32,代码来源:models.py

示例3: default

 def default(self, obj, **kwargs):
     if isinstance(obj, ObjectId):
         return str(obj)
     elif isinstance(obj, datetime.datetime):
         return json.dumps(obj, default=json_util.default)
     else:
         return JSONEncoder.default(obj, **kwargs)
开发者ID:MicroPyramid,项目名称:Mongo-Slice,代码行数:7,代码来源:views.py

示例4: default

 def default(self, obj):
     if isinstance(obj, QuerySet):
         # `default` must return a python serializable
         # structure, the easiest way is to load the JSON
         # string produced by `serialize` and return it
         return json.loads(serialize('json', obj))
     return JSONEncoder.default(self,obj)
开发者ID:opencorato,项目名称:voisietequi,代码行数:7,代码来源:views.py

示例5: __input_loop

    def __input_loop(self, protocol, base):
        """

        :type protocol server.WebSocketServerProtocol
        :param base:
        :return:
        """
        json_encoder = JSONEncoder()
        yield from protocol.send(json_encoder.encode({"message": _GET_NICK}))
        nick = yield from protocol.recv()
        self._chat_api.enter_chat(nick)
        yield from protocol.send(
            json_encoder.encode({"message": _ADD, "text": ",".join(self._chat_api.nicks_in_chat)}))
        while self._chat_api.connection_opened:
            message = yield from protocol.recv()
            self._chat_api.say_to_chat(message)
开发者ID:throwable-one,项目名称:chat-async,代码行数:16,代码来源:websocket_driver.py

示例6: __output_loop

    def __output_loop(self, protocol, base):
        """

        :type protocol server.WebSocketServerProtocol
        :param base:
        :return:
        """
        room_queue = self._chat_api.subscribe_to_chat()
        json_encoder = JSONEncoder()
        current_people = self._chat_api.nicks_in_chat
        while self._chat_api.connection_opened:
            message = yield from room_queue.get()
            yield from protocol.send(json_encoder.encode({"message": _TEXT, "text": message}))
            if current_people != self._chat_api.nicks_in_chat:
                current_people = self._chat_api.nicks_in_chat
                yield from protocol.send(
                    json_encoder.encode({"message": _ADD, "text": ",".join(self._chat_api.nicks_in_chat)}))
开发者ID:throwable-one,项目名称:chat-async,代码行数:17,代码来源:websocket_driver.py

示例7: tojsonarrays

def tojsonarrays(table, source=None, prefix=None, suffix=None,
                 output_header=False, *args, **kwargs):
    """
    Write a table in JSON format, with rows output as JSON arrays. E.g.::

        >>> from petl import tojsonarrays, look
        >>> look(table)
        +-------+-------+
        | 'foo' | 'bar' |
        +=======+=======+
        | 'a'   | 1     |
        +-------+-------+
        | 'b'   | 2     |
        +-------+-------+
        | 'c'   | 2     |
        +-------+-------+

        >>> tojsonarrays(table, 'example.json')
        >>> # check what it did
        ... with open('example.json') as f:
        ...     print f.read()
        ...
        [["a", 1], ["b", 2], ["c", 2]]

    Note that this is currently not streaming, all data is loaded into memory
    before being written to the file.

    Supports transparent writing to ``.gz`` and ``.bz2`` files.

    .. versionadded:: 0.11

    """

    encoder = JSONEncoder(*args, **kwargs)
    source = write_source_from_arg(source)
    if output_header:
        obj = list(table)
    else:
        obj = list(data(table))
    with source.open_('wb') as f:
        if prefix is not None:
            f.write(prefix)
        for chunk in encoder.iterencode(obj):
            f.write(chunk)
        if suffix is not None:
            f.write(suffix)
开发者ID:podpearson,项目名称:petl,代码行数:46,代码来源:json.py

示例8: encode_json

def encode_json(obj, inline=False, **kwargs):
  """Encode the given object as json.

  Supports objects that follow the `_asdict` protocol.  See `parse_json` for more information.

  :param obj: A serializable object.
  :param bool inline: `True` to inline all resolvable objects as nested JSON objects, `False` to
                      serialize those objects' addresses instead; `False` by default.
  :param **kwargs: Any kwargs accepted by :class:`json.JSONEncoder` besides `encoding` and
                   `default`.
  :returns: A UTF-8 json encoded blob representing the object.
  :rtype: string
  :raises: :class:`ParseError` if there were any problems encoding the given `obj` in json.
  """
  encoder = JSONEncoder(encoding='UTF-8',
                        default=functools.partial(_object_encoder, inline=inline),
                        **kwargs)
  return encoder.encode(obj)
开发者ID:caveness,项目名称:pants,代码行数:18,代码来源:parsers.py

示例9: example_default

def example_default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
开发者ID:wpr101,项目名称:Python-Cookbook,代码行数:9,代码来源:JSONexamples.py

示例10: default

 def default(self, obj):
     if isinstance(obj, CourseDetails) or isinstance(obj, course_grading.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)
开发者ID:avontd2868,项目名称:edx-platform,代码行数:9,代码来源:course_details.py

示例11: default

 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)
开发者ID:AlexxNica,项目名称:edx-platform,代码行数:9,代码来源:encoder.py

示例12: index

def index():
    if request.method == "POST":
        site_hash = sha1(request.form["url"]).hexdigest()
        zipf_profile = r.get(site_hash)
        if zipf_profile:
            return zipf_profile
        else:
            try:
                corpus = WebCorpus(request.form["url"])
            except:
                abort(404)

        e = JSONEncoder()
        zipf_profile = e.encode(corpus.freq_list)
        r.set(site_hash, zipf_profile)
        r.expire(site_hash, 120)
        resp = make_response(zipf_profile)
        return resp
    elif request.method == "GET":
        return render_template("index.html")
开发者ID:okal,项目名称:Zipfy,代码行数:20,代码来源:app.py

示例13: default

 def default(self, o):
     try:
         iterable = iter(o)
     except TypeError:
         pass
     else:
         return list(iterable)
     
     try:
         return JSONEncoder.default(self, o)
     except TypeError:
         return str(o)
开发者ID:rtirrell,项目名称:paved,代码行数:12,代码来源:paved.py

示例14: default

    def default(self, o):
        if isinstance(o, entry.Entry):
            return o.to_json()

        try:
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)

        return JSONEncoder.default(self, o)
开发者ID:GitExl,项目名称:WhackEd4,代码行数:12,代码来源:engine.py

示例15: default

 def default(self, obj):
     try:
         if isinstance(obj, Response):
             return {
                 'action': obj.action,
                 'success': obj.success,
                 'message': obj.message,
                 'responseData': obj.responseData
             }
         else:
             return JSONEncoder.default(obj)
     except Exception as e:
         pass
开发者ID:MateuszPrzybyla,项目名称:EMonopoly,代码行数:13,代码来源:Response.py


注:本文中的json.encoder.JSONEncoder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。