将 JSON 转换为哈希
Convert JSON into a Hash
我有这个 JSON,我正在尝试将它发送到邮递员的 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]
.
使用以下方法解决了我的问题:
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"}
欢迎对此代码提出任何建议。感谢您的帮助。
我有这个 JSON,我正在尝试将它发送到邮递员的 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]
.
使用以下方法解决了我的问题:
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"}
欢迎对此代码提出任何建议。感谢您的帮助。