这是我的JSON数组的值String形式(不是JSON对象)
value= "[{\"a\":\"test a\"},{\"b\":\"test b updated\"}]"
当我尝试使用将其转换为JSON时
value=value.to_json
#value= "\"[{\\\"a\\\":\\\"test a\\\"},{\\\"b\\\":\\\"test b updated\\\"}]\""
但我想要这样的价值
{"a":"test a","b":"test b updated"}
有什么建议吗?
首先,您需要将JSON字符串转换为Ruby值:
arr = JSON.parse(value)
# => [ { "a" => "test a" },
# { "b" => "test b updated" } ]
这将返回其项目为哈希的Ruby数组。
接下来,您需要将散列合并为单个散列:
combined_hash = arr.reduce({}, &:merge)
# => { "a" => "test a",
# "b" => "test b updated" }
最后,将哈希值转换回JSON:
puts combined_hash.to_json
# => {"a":"test a","b":"test b updated"}
全部一起:
arr = JSON.parse(value)
combined_hash = arr.reduce({}, &:merge)
puts combined_hash.to_json
# => {"a":"test a","b":"test b updated"}
您可以在这里查看它的运行情况:http : //ideone.com/l5BAiw
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句