首页 > 解决方案 > 是否有一种特殊的方式来解析 Ruby 中的嵌套 JSON?

问题描述

给定一个任意 JSON 字符串,例如:

"{\"foo\":\"{\\\"bar\\\":\\\"baz\\\"}\"}"

Ruby 中是否有一种方法 Ruby JSON 或一般特性来递归解析 JSON,结果是:

{ foo: { bar: :baz } }

不是在寻找什么:

o = JSON.parse(j)

JSON.parse!(o[:foo])

标签: jsonruby

解决方案


并不真地。原因是 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.


推荐阅读