我试图子类化json.JSONEncoder这样的命名元组(使用新的Python 3.6+语法定义,但它可能仍适用于输出collections.namedtuple)被序列化为JSON对象,其中元组字段对应于对象键.
例如:
from typing import NamedTuple
class MyModel(NamedTuple):
foo:int
bar:str = "Hello, World!"
a = MyModel(123) # Expected JSON: {"foo": 123, "bar": "Hello, World!"}
b = MyModel(456, "xyzzy") # Expected JSON: {"foo": 456, "bar": "xyzzy"}
Run Code Online (Sandbox Code Playgroud)
我的理解是我子类化json.JSONEncoder并覆盖它的default方法来为新类型提供序列化.然后,课程的其余部分将就递归等方面做正确的事情.因此我想出了以下内容:
class MyJSONEncoder(json.JSONEncoder):
def default(self, o):
to_encode = None
if isinstance(o, tuple) and hasattr(o, "_asdict"):
# Dictionary representation of a named tuple
to_encode = o._asdict()
if isinstance(o, datetime):
# String representation of a datetime
to_encode = …Run Code Online (Sandbox Code Playgroud) 我遇到类似于CalvinKrishy问题的问题 Samplebias的解决方案不能处理我的数据.
我使用的是Python 2.7.
这是数据:
>>> a_t = namedtuple('a','f1 words')
>>> word_t = namedtuple('word','f2 value')
>>> w1 = word_t(f2=[0,1,2], value='abc')
>>> w2 = word_t(f2=[3,4], value='def')
>>> a1 = a_t(f1=[0,1,2,3,4],words=[w1, w2])
>>> a1
a(f1=[0, 1, 2, 3, 4], words=[word(f2=[0, 1, 2], value='abc'), word(f2=[3, 4], value='def')])
Run Code Online (Sandbox Code Playgroud)
>>> w3 = {}
>>> w3['f2'] = [0,1,2]
>>> w3['value'] = 'abc'
>>> w4 = {}
>>> w4['f2'] = [3,4]
>>> w4['value'] = 'def'
>>> a2 = {}
>>> a2['f1'] = [0, 1, …Run Code Online (Sandbox Code Playgroud) 我无法转储collections.namedtuple为正确的 JSON。
首先,考虑使用自定义 JSON 序列化程序的官方示例:
import json
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, complex):
return [obj.real, obj.imag]
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
json.dumps(2 + 1j, cls=ComplexEncoder) # works great, without a doubt
Run Code Online (Sandbox Code Playgroud)
其次,现在考虑以下示例,它告诉 Python 如何对Friend对象进行 JSONize:
import json
class Friend():
""" struct-like, for storing state details of a friend """
def __init__(self, _id, f_name, l_name):
self._id = _id
self.f_name = f_name
self.l_name = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用namedtuple将Python对象序列化为JSON.但是我得到了这个错误.谷歌没有帮助.
Traceback (most recent call last):
File "cpu2.py", line 28, in <module>
cpuInfo = collections.namedtuple('cpuStats',('cpu.usr', ('str(currentTime) + " "
+str(cpuStats[0]) + " host="+ thisClient')), ('cpu.nice', ('str(currentTime) + " "
+str(cpuStats[1]) + " host="+ thisClient')), ('cpu.sys',('str(currentTime) + " "
+str(cpuStats[2]) + " host="+ thisClient')), ('cpu.idle',('str(currentTime) + " "
+str(cpuStats[3]) + " host="+ thisClient')))
TypeError: namedtuple() takes at most 4 arguments (5 given)
Run Code Online (Sandbox Code Playgroud)