json - 是否有一种特殊的方式来解析 Ruby 中的嵌套 JSON?
问题描述
给定一个任意 JSON 字符串,例如:
"{\"foo\":\"{\\\"bar\\\":\\\"baz\\\"}\"}"
Ruby 中是否有一种方法 Ruby JSON 或一般特性来递归解析 JSON,结果是:
{ foo: { bar: :baz } }
我不是在寻找什么:
o = JSON.parse(j)
JSON.parse!(o[:foo])
解决方案
并不真地。原因是 JSON 字符串只是一个字符串,所以没有办法只知道它是否是可解析的 JSON。
您可以尝试将所有内容解析为 JSON,如下所示:
def recursive_parse_hash_from_json(str)
parsed = JSON.parse(str)
parsed.reduce({}) do |memo, (key, val)|
new_val = val.is_a?(String) ? recursive_parse_hash_from_json(val) : val
memo.merge({ key => val})
end
rescue JSON::ParserError
str
end
json = {"a" => { "b" => "c" }.to_json, "d" => "e"}.to_json
recursive_parse_hash_from_json(json)
# => {"a"=>{"b"=>"c"}, "d"=>"e"}
但这有一些极端情况——如果其中一个字符串恰好是有效的 JSON,但不打算如此呢?
Depending on your use case, the above method may work for you though. However I wouldn't recommend doing this for anything other than analytics. E.g. if you're working with user-supplied strings and this actually controls business logic your application, you woudln't want to risk parsing something as the wrong data type.
推荐阅读
- vue.js - Vue.js;如何获取另一个框架使用的 cookie?
- php - nginx php-fpm 502 错误网关
- c# - Unity检查碰撞器是否是生成的预制件的类型
- excel - 如何使用员工 ID 作为标识符将多个工作表中的数据复制到一个工作表中
- python - 从决策树中获取值
- jsonata - 使用 JSONata 对 JSON 对象中的键进行 alpha 排序
- r - 在数据帧上查找最大值和最小值,忽略 NA
- java - data.sql 文件未在 Spring Boot 中将数据泵送到表中
- angular - 按服务取消当前请求,只获取最后一个请求的结果
- php - 结合双foreach循环