Julia中将自定义Struct/Type结构体转换为Dict字典的问题咨询
Julia 结构体转Dict的可行实现方案
这里针对你给出的结构体定义,提供三种不同场景的实现方法:
方法1:通用非嵌套转换
仅转换外层结构体字段,嵌套的结构体实例会直接作为Dict的值保留:
function struct2dict(s) Dict( fn => getproperty(s, fn) for fn in fieldnames(typeof(s)) ) end
调用示例:
# 构造测试实例 a = A(1, 2) s = S("val1", "val2", 100, a) struct2dict(s) # 返回结果:Dict(:atrr1 => "val1", :attr2 => "val2", :attr3 => 100, :attr4 => A(1, 2))
如果需要字典的键为字符串而非Symbol类型,把代码中
fn替换为string(fn)即可。
方法2:支持嵌套递归转换
如果需要把嵌套的A类型实例也自动转换为Dict,使用递归实现即可:
function nested_struct2dict(s) T = typeof(s) # 字符串属于结构体类型但不需要拆解,单独排除 if isstructtype(T) && !(T <: AbstractString) return Dict( fn => nested_struct2dict(getproperty(s, fn)) for fn in fieldnames(T) ) else return s end end
调用示例:
nested_struct2dict(s) # 返回结果:Dict(:atrr1 => "val1", :attr2 => "val2", :attr3 => 100, :attr4 => Dict(:A1 => 1, :A2 => 2))
方法3:基于第三方包实现
如果项目中已经引入了StructTypes和JSON3依赖,可以直接用包提供的能力实现转换,不需要手写工具函数:
using StructTypes, JSON3 # 给自定义结构体注册类型注解 StructTypes.@struct_struct A StructTypes.@struct_struct S # 直接转换为Dict JSON3.@dict s
内容的提问来源于stack exchange,提问作者ahm5
相关产品推荐
相关产品推荐

