jsonruby-on-railsrubyhashstring-substitution

Replace Json string in Ruby


First, I have a json:

 json = "{\"string_1\": \"{{string_1_value}}\", \"number_1\": \"{{number_1_value}}\"}"

And this hash:

hash = {
 "{{string_1_value}}" => "test" //string
 "{{number_1_value}}" => 2 //integer
}

What I'd like to do is to replace json with this hash and generate below json.

"{\"string_1\": \"test\", \"number_1\": 2}"

When I do this by String#gsub, I got an Error.

    hash.map {|k, v| json.gsub!(k, v)}
 => TypeError (no implicit conversion of Integer into String)

I don't want 2 to be string, i.e.) "{"string_1": "test", "number_1": "2"}"

Do you have any idea? Thank you in advance.


Solution

  • First, in ruby comments are marked by # not //. And remember about the comma in hash.

    gsub is not the fastest way to replace things, it's better to convert json to regular hash and then convert it again to json.

    require 'json'
    
    json = "{\"string_1\": \"{{string_1_value}}\", \"number_1\": \"{{number_1_value}}\"}"
    hash = {
     "{{string_1_value}}" => "test", #string
     "{{number_1_value}}" => 2 #integer
    }
    
    # First you should parse your json and change it to hash:
    parsed_json = JSON.parse(json)
    # Then create keys array
    keys = parsed_json.keys
    # Create new empty hash
    new_hash = {}
    # And now fill new hash with keys and values 
    # (take a look at to_s, it converts values to a String)
    hash.each.with_index do |(_k, v), i|
      new_hash[keys[i]] = v.to_s
    end
    # Convert to json at the end
    new_hash.to_json
    #  => "{\"string_1\":\"test\",\"number_1\":\"2\"}"