我有这个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[:values]
。
答案 0 :(得分:2)
使用以下方式解决了我的问题:
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"}
随意对此代码提出任何建议。谢谢你的帮助。