Search code examples
jsonrubyhashstringify

ruby deep stringify hash


I would like to deep stringify hash in ruby like each nested hash need to be also string

input:

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

output:

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

is there any ready to use function or gem to achieve this result?


Solution

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

    But the question is, why you need to do this?