簡體   English   中英

替換 Ruby 中的 Json 字符串

[英]Replace Json string in Ruby

首先,我有一個 json:

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

而這個 hash:

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

我想做的是用這個 hash 替換 json 並在 json 下面生成。

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

當我通過String#gsub執行此操作時,出現錯誤。

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

我不希望2是字符串,即) "{"string_1": "test", "number_1": "2"}"

你有什么主意嗎? 先感謝您。

首先,在 ruby 中,注釋用#而不是//標記。 記住 hash 中的逗號。

gsub不是最快的替換東西的方法,最好將 json 轉換為常規的 hash 然后再轉換為 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.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\"}" 

您可以使用String#gsub將模式替換為所需的值,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM