I’m building a publication in Ruby/Sinatra which responds to a GET call (from the API server, which I don’t have control of) with two parameters (“local_delivery_time” and “tubelines”) in JSON. At the moment an example call is;
So once it’s unencoded from uri, the “tubelines” parameter is coming through as a Ruby hash (I believe?) i.e.
{“Bakerloo”=>”0”, “Central”=>”0”, “Circle”=>”0”, “District”=>”0”, “DLR”=>”0”, “Hammersmith and City”=>”0”, “Jubilee”=>”0”, “Metropolitan”=>”1”, “Northern”=>”0”, “Overground”=>”1”, “Piccadilly”=>”0”, “Victoria”=>”0”, “Waterloo and City”=>”0”}
but when I try to run this .each code over it (to push the keys with value “1” to another array);
tubelines.each do |key, value|
if value == "1"
@selectedlines.push(key)
end
end
I get this error “NoMethodError – undefined method `each’ for #” and it shows the hash with escaped quotes. Like this;
{\”Bakerloo\”=>\”0\”, \”Central\”=>\”0\”, \”Circle\”=>\”0\”, \”District\”=>\”0\”, \”DLR\”=>\”0\”, \”Hammersmith and City\”=>\”0\”, \”Jubilee\”=>\”0\”, \”Metropolitan\”=>\”1\”, \”Northern\”=>\”0\”, \”Overground\”=>\”1\”, \”Piccadilly\”=>\”0\”, \”Victoria\”=>\”0\”, \”Waterloo and City\”=>\”0\”}
I can’t change the format of the call, so how can I deal with the escaped quotes so I can use the hash? I’ve tried parsing it through JSON, but the parser seems to have the same problem with the escaped quotes (it returns an unexpected token error) and when I hand type in the exact same hash, the code works perfectly.
I’ve seen lots of questions about encoding JSON objects and escaped quotes, but haven’t found any about dealing with escaped quotes when receiving a JSON object or call…
I’m with Frederick Cheung on this, it’s a messed up way to send data. How about getting them to send JSON with a POST request instead? It’s a lot easier to handle:
They just send there POST request will all the data in the “data:” key.
It’s possible that will work with a GET too, but main thing is not to send crazy stuff in the url as it just makes your life hard. I’m sure you’ll have fun passing that on to the people running the server! 🙂