[英]Putting Variable with in single quotes?
大家好,我正在向Campaign Monitor API發出請求,並且數據必須以單引號作為字符串但以JSON格式保存。 由於必須是單引號,因此我無法輸入任何變量值。 下面是代碼。
response = HTTParty.post(url,
:basic_auth => auth, :body => '{
"EmailAddress":"js@mike.com",
"Name":"#{@fname}",
"CustomFields":[
{
"Key":"firstName",
"Value":"#{@fname}"
},
{
"Key":"country",
"Value":"#{@country}"
}
],
"Resubscribe":true,
"RestartSubscriptionBasedAutoresponders":true
}')
我嘗試了幾種不同的方法,例如將字符串分解並將其與帶雙引號的變量一起拼湊回去,但是對於成功的請求來說,它也同樣是失敗的。
您可以構建Ruby哈希並將其轉換為JSON,而不是手動構建JSON結構:
require 'json'
data = {
'EmailAddress' => 'js@mike.com',
'Name' => @fname,
'CustomFields' => [
{ 'Key' => 'firstName', 'Value' => @fname },
{ 'Key' => 'country', 'Value' => @country }
],
'Resubscribe' => true,
'RestartSubscriptionBasedAutoresponders' => true
}
response = HTTParty.post(url, basic_auth: auth, body: data.to_json)
另請注意,Campaign Monitor API有一個Ruby gem: createsend-ruby
使用gem,以上代碼可轉換為:
custom_fields = [
{ 'Key' => 'firstName', 'Value' => @fname },
{ 'Key' => 'country', 'Value' => @country }
]
response = CreateSend::Subscriber.add(auth, list_id, 'js@mike.com', @fname, custom_fields, true, true)
您可以嘗試使用heredoc :
response = HTTParty.post(url,
:basic_auth => auth, :body => <<-BODY_CONTENT
{
"EmailAddress":"js@mike.com",
"Name":"#{@fname}",
"CustomFields":[
{
"Key":"firstName",
"Value":"#{@fname}"
},
{
"Key":"country",
"Value":"#{@country}"
}
],
"Resubscribe":true,
"RestartSubscriptionBasedAutoresponders":true
}
BODY_CONTENT
)
您可以按照此處的說明使用heredoc
如果在標識符周圍加上雙引號,也會遵循雙引號規則。 但是,不要在終止符兩邊加上雙引號。
puts <<"QUIZ"
Student: #{name}
1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ
您可以在此處使用以下文件:
name = 'John'
<<EOS
This is #{name}
EOS
另外,您可以使用靈活的引號,它們可以處理'
和"
字符:
name = 'John'
%{
This is #{name}
}
靈活的報價適用於%()
和%!!
也一樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.