红宝石深字符串化哈希

时间:2020-08-25 08:10:58

标签: json ruby hash stringify

我想在ruby中对哈希进行深度字符串化,就像每个嵌套的哈希也必须是字符串一样

输入:

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

输出:

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

有没有可以使用的函数或gem来实现此结果?

2 个答案:

答案 0 :(得分:3)

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\\\"}\"}"

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

答案 1 :(得分:0)

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 = /(?="[^{}]*\})/

它匹配双引号之前的零宽度位置,后跟左括号以外的任意数量的字符,后跟右括号,这意味着双引号位于由括号分隔的字符串中。像在问题中给出的示例一样,这假定大括号没有嵌套。

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\" } }