Replace Json string in Ruby

696 Views Asked by At

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.

2

There are 2 best solutions below

0
stolarz On BEST ANSWER

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\"}" 
0
engineersmnky On

You can use the Regexp,Hash version of String#gsub to just substitute the patterns with the desired values as follows:

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

original_hash= {
 "{{string_1_value}}" => "test", #string
 "{{number_1_value}}" => 2 #integer
}

#Convert JSON to hash and invert the key value pairs 
parsed_json = JSON.parse(json_string).invert
#=>{"{{string_1_value}}"=>"string_1", "{{number_1_value}}"=>"number_1"}

# Convert the hash to JSON and substitute the patterns 
original_hash.to_json.gsub(/\{\{.+?\}\}/, parsed_json) 
#=> "{\"string_1\":\"test\",\"number_1\":2}"