gpt4 book ai didi

ruby-on-rails - 将 JSON 转换为哈希

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:40 24 4
gpt4 key购买 nike

我有这个 JSON,我正在尝试将它从 Postman 发送到 Rails API:

{"object": 
{
"type": "out",
"vars":
{
"x": "x",
"y": "y"
},
"values":
{
"ts": "timestamp",
"ok":
{
"total": 2,
"min": "x",
"max": "y"
},
"error":
{
"total": 2,
"error1": "first",
"error2": "second"
}
}
}
}

我需要在我的模型中将其转换为一个Hash,以便我可以使用before_create 对其进行操作。这是我带来的:

object = self.to_json # => converts object to json
object = JSON.parse(object) # => converts json to hash

第一个问题:我明白了(id=>nil 不相关,因为它将自动插入到数据库中):

 {"id"=>nil, "type"=>"out", "vars"=>{"x"=>"x", "y"=>"y"}, "values"=>{"ts"=>"timestamp", "ok"=>"{\"total\"=>2, \"min\"=>\"x\", \"max\"=>\"y\"}", "error"=>"{\"total\"=>2, \"error1\"=>\"first\", \"error2\"=>\"second\"}"}, "created_at"=>"2015-01-29T15:45:01.329Z", "updated_at"=>"2015-01-29T15:45:01.329Z"}

当我尝试操作 object["values"]["ok"] 时,Rails 发送错误:

unexpected token at '"{\"total\"=\u003e2, \"min\"=\u003e\"x\", \"max\"=\u003e\"y\"}"'

第二个问题:我只能调用object["values"],我想用一个符号来调用它,而不是字符串object[:值]

最佳答案

使用以下方法解决了我的问题:

object = self.as_json.with_indifferent_access
# => allowing me to use a symbol key instead of a string

ok_vals = object[:values][:ok].as_json.gsub(/\=\>/, ':')
# => allowing to change json string '{"val1"=>"val1", "val2"=>"val2"}' to '{"val1":"val1", "val2":"val2"}'
ok_vals = JSON.parse(ok_vals)
# => which transform json string to hash {val1: "val1", val2: "val2"}

请随时对此代码提出任何建议。感谢您的帮助。

关于ruby-on-rails - 将 JSON 转换为哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28219166/

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