sam.roberts55 sam.roberts55 - 5 months ago 8
JSON Question

issue with render json for array

I have this array coming from my server. Which is returned like this when i use 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


so i just tried to do this:

price1.each do |price11|
price11.json {render json: price11.as_json}
end


However this returns this error:

NoMethodError (undefined method `json' for ["formatted_total_price", "£66.00"]:Array):


What I'm wanting is to have the
formatted_total_price
and the
£66.00
to match up to look like this:

"formatted_total_price":"£66.00"


Heres the actual code i have:

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


Edit
Ok so heres what i have:

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 &#64 extra £4.95 per ticket
ticket_desc
Later Owl + Chance For VIP Upgrade
ticket_desc
VIP Ticket
ticket_desc
VIP Ticket + Collector Ticket &#64 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


What i want is kinda the same as last time but more like this:

"formatted_total_price" : "£66.00",
"ticket_desc" : "Later Owl Ticket"


Also if ticket_desc has anything that include a
+
symbol i want it ignored (i can do this myself unless you know of a better way!!)

Answer
a = Array.new

price1.each do |p|
    a.merge({p[0] => p[1]})
end

render json: a.to_json

or simply you can do

price1.map{|a| { a[0] => a[1] } }.to_json
Comments