我需要从form_tag
生成JSON。我想要生成的结构是这样的:
"recipients": [
{
"account": {
"accountId": "4",
"account": "4",
"branch": "4"
},
"order": {
"orderId": "4",
"dateTime": "4",
"description": "4"
},
"amount": "3",
"mediatorFee": "0",
"currency": "0"
},
{
"account": {
"accountId": "4",
"account": "4",
"branch": "4"
},
"order": {
"orderId": "4",
"dateTime": "4",
"description": "4"
},
"amount": "3",
"mediatorFee": "0",
"currency": "0"
}
]
我这样做:
<fieldset>
<legend>Recipients</legend>
<p>Account</p>
<div>
<%= label_tag 'AccountId' %>
<%= text_field_tag 'recipients[][account][accountId]', nil , class: "form-control" %>
</div>
<div>
<%= label_tag 'Account' %>
<%= text_field_tag 'recipients[][account][account]', nil , class: "form-control" %>
</div>
<div>
<%= label_tag 'Branch' %>
<%= text_field_tag 'recipients[][account][branch]', nil , class: "form-control" %>
</div>
<p>Order</p>
<div>
<%= label_tag 'OrderId' %>
<%= text_field_tag 'recipients[][order][orderId]', nil , class: "form-control" %>
</div>
<div>
<%= label_tag 'DateTime' %>
<%= text_field_tag 'recipients[][order][dateTime]', nil , class: "form-control" %>
</div>
<div>
<%= label_tag 'Description' %>
<%= text_field_tag 'recipients[][order][description]', nil , class: "form-control" %>
</div>
<p>Recipients</p>
<div>
<%= label_tag 'Amount' %>
<%= text_field_tag 'recipients[][amount]', (params['recipients[][amount]'] or 0) , class: "form-control" %>
</div>
<div>
<%= label_tag 'Mediator Fee' %>
<%= text_field_tag 'recipients[][mediatorFee]', (params['recipients[][mediatorFee]'] or 0) , class: "form-control" %>
</div>
<div>
<%= label_tag 'Currency' %>
<%= text_field_tag 'recipients[][currency]', (params['recipients[][currency]'] or 0) , class: "form-control" %>
</div>
</fieldset>
我的控制器是:
require 'rubygems'
require 'httparty'
require 'json'
require 'digest'
class PaymentsController < ApplicationController
def index
end
def sendPayment
params.delete :utf8
params.delete :commit
params.delete :controller
params.delete :action
@jsonParams = params
puts @jsonParams.to_json
@result = HTTParty.post('http://url.url.com'.to_str,
:body => @jsonParams.to_json,
:headers => { 'Content-Type' => 'application/json',
'Api-Access-Key' => 'xxxxxxxxxx',
'Transaction-Hash' => 'dsa' } )
puts @result
# redirect_to root_path
end
end
我需要在这个数组中添加更多对象。我怎么能这样做?
答案 0 :(得分:1)
要让浏览器理解 - 您只需要复制字段,因为您已经在字段名称中使用了数组标记,但是机架查询解析器中似乎存在一个错误,它会使深层嵌套中的数据丢失:
q = Rack::Utils.build_nested_query(
{a:[{b:{c:"this will be lost"}}, {b:{c:2}}]}
) #=> "a[][b][c]=this+will+be+lost&a[][b][c]=2"
Rack::Utils.parse_nested_query(q) # => {"a"=>[{"b"=>{"c"=>"2"}}]}
虽然没有深度嵌套,但它有效:
Rack::Utils.parse_nested_query(Rack::Utils.build_nested_query({a:[{b:"will not be lost"}, {b:2}]})) #=> {"a"=>[{"b"=>"will not be lost"}, {"b"=>"2"}]}
因此,作为一种解决方法,您可以为字段recipients[0][account][accountId]
,recipients[1][account][accountId]
等命名,然后重新组合数组:
params["recipients"] = params["recipients"].values if params["recipients"].is_a?(Hash)