本文整理汇总了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)
示例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)
示例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)
示例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)
示例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)
示例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)}))
示例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)
示例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)
示例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)
示例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)
示例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)
示例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")
示例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)
示例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)
示例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