ruby 深度字符串化哈希

ruby deep stringify hash

我想在 ruby 中深度字符串化哈希,就像每个嵌套哈希也需要是字符串

输入:

{"command": "subscribe", "identifier": { "channel": "TxpoolChannel" } }

输出:

"{\"command\":\"subscribe\",\"identifier\":\"{\\"channel\\":\\"TxpoolChannel\\"}\"}"

是否有现成的函数或gem来实现这个结果?

require 'json'

def deep_to_json(h)
  h.transform_values{|v| v.is_a?(Hash) ? deep_to_json(v) : v}.to_json
end

deep_to_json({"command": "subscribe", "identifier": { "channel": "TxpoolChannel" } })
#=> "{\"command\":\"subscribe\",\"identifier\":\"{\\"channel\\":\\"TxpoolChannel\\"}\"}"

但问题是,为什么你需要这样做?

str = '{"co": "su", "id": {"ch": "Tx"}, "pig": {1: :b}, "cat": { "dog": "Woof" } }'
  #=> "{\"co\": \"su\", \"id\": {\"ch\": \"Tx\"}, \"pig\": {1: :b}, \"cat\": { \"dog\": \"Woof\" } }"
r = /
    (?=       # begin a positive lookahead
      "       # match a double-quote
      [^{}]*  # match 0* characters other than '{' and '}'
      \}      # match '}'
    )         # end positive lookahead 
    /x        # invoke free-spacing regex definition mode

这个正则表达式约定俗成如下

r = /(?="[^{}]*\})/

它匹配 zero-width 位置前面的 double-quote 后跟除左大括号以外的任意数量的字符,后跟右大括号,这意味着 double-quote 是在由大括号分隔的字符串中。这假设,如问题中给出的示例,大括号未嵌套。

See it at rebular.com

    s = str.gsub(r, "\")
      #=> "{\"co\": \"su\", \"id\": {\\"ch\\": \\"Tx\\"}, \"pig\": {1: :b}, \"cat\": { \\"dog\\": \\"Woof\\" } }" 
    puts s
    {"co": "su", "id": {\"ch\": \"Tx\"}, "pig": {1: :b}, "cat": { \"dog\": \"Woof\" } }