【问题标题】:ruby deep stringify hashruby 深度字符串化哈希
【发布时间】:2020-12-13 21:30:21
【问题描述】:

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

输入:

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

输出:

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

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

【问题讨论】:

  • 您的输入看起来像一个 JSON 字符串。也许你一开始就不应该把它当作一个 Ruby 文字?
  • ... 为什么要两次转义内部哈希?
  • 我正在尝试将 rails cable 与外部软件连接,并且 action cable 消息需要采用这种格式

标签: json ruby hash stringify


【解决方案1】:
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\\\"}\"}"

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

【讨论】:

  • 我正在尝试将rails动作电缆与外部软件连接,动作电缆消息需要采用这种格式,所以我发送的是普通json并希望将这个json处理为动作电缆json格式跨度>
  • 你提出的问题没有其他答案那么有趣。
  • @CarySwoveland 我对简单的to_json 无法解决 OP 的问题这一事实很感兴趣。
【解决方案2】:
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\" } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 2012-08-10
    • 2016-10-31
    • 2012-03-31
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多