我有这个数组来自我的服务器。当我使用puts:
时会返回这样的内容formatted_total_price
£66.00
formatted_total_price
£128.00
formatted_total_price
£246.00
formatted_total_price
£243.20
formatted_total_price
£242.86
formatted_total_price
£242.50
所以我试着这样做:
price1.each do |price11|
price11.json {render json: price11.as_json}
end
然而,这会返回此错误:
NoMethodError (undefined method `json' for ["formatted_total_price", "£66.00"]:Array):
我想要的是让formatted_total_price
和£66.00
匹配起来像这样:
"formatted_total_price":"£66.00"
这是我拥有的实际代码:
doc.xpath("//script[@type='text/javascript']/text()").each do |text|
if text.content =~ /more_options_on_polling/
price1 = text.to_s.scan(/\"(formatted_total_price)\":\"(.+?)\"/).uniq
description = text.to_s.scan(/\"(ticket_desc)\":\"(.+?)\"/).uniq
price = price1 + description
price1.each do |price11|
price11.json {render json: price11.as_json}
end
end
修改 好的,这就是我所拥有的:
formatted_total_price
£66.00
formatted_total_price
£128.00
formatted_total_price
£246.00
formatted_total_price
£243.20
formatted_total_price
£242.86
formatted_total_price
£242.50
ticket_desc
Later Owl Ticket
ticket_desc
Later Owl Ticket+Collector Ticket @ extra £4.95 per ticket
ticket_desc
Later Owl + Chance For VIP Upgrade
ticket_desc
VIP Ticket
ticket_desc
VIP Ticket + Collector Ticket @ extra £4.95 per ticket
ticket_desc
Skydeck Package
ticket_desc
5 Person Skydeck Table
ticket_desc
7 Person Skydeck Table
ticket_desc
10 Person Skydeck Table
我想要的是和上次一样,但更像是这样:
"formatted_total_price" : "£66.00",
"ticket_desc" : "Later Owl Ticket"
此外,如果ticket_desc有任何包含+
符号的内容,我希望它被忽略(我可以自己做,除非你知道更好的方法!!)
答案 0 :(得分:1)
a = Array.new
price1.each do |p|
a.merge({p[0] => p[1]})
end
render json: a.to_json
或者只是你可以做
price1.map{|a| { a[0] => a[1] } }.to_json