在JSON字符串中动态注入值

时间:2017-07-10 06:09:49

标签: json ruby

我想动态地在字符串中注入值,下面是我的代码:

arg = [{:state=>"running",:instance_id=>"i-0e0082f20149e5df0"},
        {:state=>"running",:instance_id=>"i-0e0082f20149e5df0"}]
argv = ['{ "tray" : "0", "onebox" : "False", "args" : #{arg},"param" : []}']
options = JSON.parse(argv[0] || "{}", :symbolize_names => true)

上面的代码显示了JSON解析错误。我怎样才能动态注入args的值?有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

如Sergio插值所述,单引号字符串不起作用。

arg = [{:state=>"running",:instance_id=>"i-0e0082f20149e5df0"},
    {:state=>"running",:instance_id=>"i-0e0082f20149e5df0"}]
argv = [ '{ "tray" : "0", "onebox" : "False", "args" : ' + arg.to_json + ',"param" : []}' ]
options = JSON.parse(argv[0] || "{}", :symbolize_names => true)