我已经设置了一些我自己的类,它们是字典的子类,以像它们一样工作。然而,当我想将它们编码为 JSON(使用 Python)时,我希望它们以一种我可以将它们解码回原始对象而不是字典的方式进行序列化。
所以我想支持我自己的类(继承自 dict)的嵌套对象。
我曾尝试过类似的东西:
class ShadingInfoEncoder(json.JSONEncoder):
def encode(self, o):
if type(o).__name__ == "NodeInfo":
return '{"_NodeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif type(o).__name__ == "ShapeInfo":
return '{"_ShapeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif type(o).__name__ == "ShaderInfo":
return '{"_ShaderInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
return super(ShadingInfoEncoder, self).encode(o)
和:
class ShadingInfoEncoder(json.JSONEncoder):
def encode(self, o):
if isinstance(o, NodeInfo):
return '{"_NodeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif isinstance(o, ShapeInfo):
return '{"_ShapeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif isinstance(o, ShaderInfo):
return '{"_ShaderInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
return super(ShadingInfoEncoder, self).encode(o)
它通常有效,但当它们嵌套或第一个被转储的对象不是这些类型时则无效。因此,这仅在输入对象属于该类型时才有效。但不是嵌套时。
我不确定如何递归地编码这个 JSON,以便所有嵌套/包含的实例都根据相同的规则编码。
我认为使用 JSONEncoder 的默认方法会更容易(因为只要对象是不受支持的类型就会调用它。)但是由于我的对象是从 dict 继承的,所以它们被解析为字典而不是被处理“默认”方法。
最佳答案
我最终做了以下事情。
class ShadingInfoEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
jsonPlaceholderNames = (("_ShaderInfo", ShaderInfo),
("_ShapeInfo", ShapeInfo),
("_NodeInfo", NodeInfo))
for jsonPlaceholderName, cls in customIterEncode:
if isinstance(o, cls):
yield '{"' + jsonPlaceholderName+ '": '
for chunk in super(ShadingInfoEncoder, self)._iterencode(o, markers):
yield chunk
yield '}'
break
else:
for chunk in super(ShadingInfoEncoder, self)._iterencode(o, markers):
yield chunk
我认为这不是最好的方法,但我在这里分享它,看看是否有其他人可以告诉我我做错了什么,并告诉我最好的方法!
请注意,我使用的是嵌套元组而不是字典,因为我想保持它们的列出顺序,这样我就可以 - 在本例中 - 如果 ShaderInfo 是从 NodeInfo 继承的对象,则覆盖 ShaderInfo 成为 _NodeInfo。
我的解码器设置为按照(简化和部分代码)的方式执行某些操作:
class ShadingInfoDecoder(json.JSONDecoder):
def decode(self, obj):
obj = super(ShadingInfoDecoder,self).decode(s)
if isinstance(obj, dict):
decoders = [("_set",self.setDecode),
("_NodeInfo", self.nodeInfoDecode),
("_ShapeInfo", self.shapeInfoDecode),
("_ShaderInfo", self.shaderInfoDecode)]
for placeholder, decoder in decoders:
if placeholder in obj:
return decoder(obj[placeholder])
else:
for k in obj:
obj[k] = self.recursiveDecode(obj[k])
elif isinstance(obj, list):
for x in range(len(obj)):
obj[x] = self.recursiveDecode(obj[x])
return obj
def setDecode(self, v):
return set(v)
def nodeInfoDecode(self, v):
o = NodeInfo()
o.update(self.recursiveDecode(v))
return o
def shapeInfoDecode(self, v):
o = ShapeInfo()
o.update(self.recursiveDecode(v))
return o
def shaderInfoDecode(self, v):
o = ShaderInfo()
o.update(self.recursiveDecode(v))
return o
nodeInfoDecode 方法获取输入的字典并使用它来初始化创建和返回的 NodeInfo 对象的值/属性。
更多信息:
另请参阅我在 How to change json encoding behaviour for serializable python object? 上的回答
关于python - 覆盖继承的默认支持对象(如 dict、list)的嵌套 JSON 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16361223/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信