1 和 b->2 最佳答案 尝试使用: a = A.new(*JSON[jso-6ren">
gpt4 book ai didi

ruby - 如何将 JSON 值传递给 Struct Ruby 对象?

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:22 25 4
gpt4 key购买 nike

给定一个 JSON 对象

{"a": 1, "b":2}

以及从结构派生的值对象:

class A < Stuct.new(:a, :b)
end

我如何创建一个具有 JSON 值的 A 实例?

我正在尝试:

 a = A.new(JSON.parse({a:1,b:2}.to_json).values)
=> #<struct A a=[1, 2], b=nil>

但我希望 a->1 和 b->2

最佳答案

尝试使用:

a = A.new(*JSON[json].values)
a.class # => A < #<Class:0x00000102955828>

问题是 values 返回一个数组,但您需要数组的各个元素。使用 * 将数组“splats”回其组件,当您将值传递给 new 时,这会让 Struct 很高兴。


编辑:

This will fail if the ordering of the JSON and the Struct do not match!

这会强制值的顺序。

a = A.new(*JSON[json].values_at('a', 'b'))
{
:a => 1,
:b => 2
}
a.class # => A < #<Class:0x00000102955828>

JSON 保留了哈希插入顺序,Ruby 也是如此,因此,Ruby 渲染和解析的 JSON 将是正确的。由不保留顺序的东西呈现的 JSON 可能是个问题,但 values_at 解决了这个问题。

请注意,JSON 将符号转换为字符串,因此传递给 values_at 的键必须是字符串,而不是符号。

关于ruby - 如何将 JSON 值传递给 Struct Ruby 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14943085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com