I'm trying to load images from Flickr's API into a Ruby on Rails app, but I'm getting "Unexpected Token" on my JSON.parse() line.
I found another response here where the returned JSON had it's double quotes escaped out, and the solution was to add the .gsub thing to the end, but I'm still getting an error.
Anyone know what the problem is?
def add
#jsonresults = open("http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=bb398c11934abb6d51bdd720020f6a4a&per_page=1&page=1&format=json&nojsoncallback=1").read
#images = JSON.parse(#jsonresults.to_json.gsub('\"', '"'))
end
The error:
JSON::ParserError in ImagesController#add
757: unexpected token at '"{"photos":{"page":1, "pages":500, "perpage":1, "total":500, "photo":[{"id":"8234011021", "owner":"24066605#N07", "secret":"b4c05df8c5", "server":"8341", "farm":9, "title":"Crescent Lake", "ispublic":1, "isfriend":0, "isfamily":0}]}, "stat":"ok"}"'
The json returned by the call looks fine. Change your parsing to this:
#images = JSON.parse(#jsonresults)
That is not valid JSON. The outer set of double-quotes do not belong. This is the valid version:
'{"photos":{"page":1, "pages":500, "perpage":1, "total":500, "photo":[{"id":"8234011021", "owner":"24066605#N07", "secret":"b4c05df8c5", "server":"8341", "farm":9, "title":"Crescent Lake", "ispublic":1, "isfriend":0, "isfamily":0}]}, "stat":"ok"}'
Related
I want to use openweather in my app.
It works good to write directly api_key.
However I introduce ENV, It won't work.
Anyone konws how to fix it?
quesiton is bellow
static_pages_controller.rb
...
uri = URI.parse('http://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=ENV['OPEN_WEATHER_API_KEY']')
json = Net::HTTP.get(uri)
res = JSON.parse(json)
#wind = res['wind']['speed']
#humidity = res['main']['humidity']
#clouds = res['clouds']['all']
...
.env
OPEN_WEATHER_API_KEY=20ab....
error code
/Users/sy/env2/ji-boys/app/controllers/static_pages_controller.rb:19:
syntax error,
unexpected tCONSTANT, expecting ')' ...appid=ENV['OPEN_WEATHER_API_KEY']') ... ^~~~~~~~~~~~~~~~~~~~
/Users/sy/env2/ji-boys/app/controllers/static_pages_controller.rb:19:
syntax error, unexpected ')', expecting end ...d=ENV['OPEN_WEATHER_API_KEY']') ... ^
I think ...appid=ENV['OPEN_WEATHER_API_KEY'].. is wrong.
Searching for how to write code, but can't find that.
Anyone knows this, please teach me how to fix it.
Thank you for reading this.
You need to do string interpolation to embed value
URI.parse("http://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=#{ENV['OPEN_WEATHER_API_KEY']}")
I'm trying to provide a good experience to users that are using JSON and the parser is on the backend (Ruby).
Most of the time, when you get a badly formatted JSON payload the error is of the format XXX unexpected token at '<entire payload here>'. That's not very user-friendly nor practical.
My question is: Is there a list of the XXX error codes that could help create better error messages that could be understood by beginners and not-really-tech-people?
Thanks!
XXX in this kind of errors is not a special code of the error. It is just a line number from the file where this error was raised. For example, for Ruby 2.5.1 you'll get JSON::ParserError (765: unexpected token at https://github.com/ruby/ruby/blob/v2_5_1/ext/json/parser/parser.rl#L765
You can find a list in the documentation for the module.
Think this covers it:
JSON::JSONError
JSON::GeneratorError
JSON::GenericObject
# The base exception for JSON errors.
JSON::MissingUnicodeSupport
# This exception is raised if the required unicode support is missing on the system. Usually this means that the iconv library is not installed.
JSON::NestingError
# This exception is raised if the nesting of parsed data structures is too deep.
JSON::ParserError
# This exception is raised if a parser error occurs.
JSON::UnparserError
# This exception is raised if a generator or unparser error occurs.
JSON::JSONError is the parent class, so you can rescue from that and provide per-error-class messages as needed.
I feel it's worth noting that in my experience the vast majority of errors relating to JSON are of the class JSON::ParserError. Another common issue worth considering is getting ArgumentError if nil is passed as an argument.
As an example of how this could be used, you could work with something like the following:
begin
JSON.parse(your_json)
rescue JSON::JSONError, ArgumentError => e
{ error: I18n.t(e.to_s) } # <- or whatever you want to do per error
end
Hope that helps - let me know how you get on :)
the String that I'm trying to parse is:
{\"user_name\":\"test#test.com\",\"pass\":\"bla\"}
[3] pry(#<Flockers::WebApp>)> JSON.parse(request.body.read)
JSON::ParserError: A JSON text must at least contain two octets!
from c:/WebTools/Ruby193/lib/ruby/gems/1.9.1/gems/json_pure-1.8.1/lib/json/commo
n.rb:155:in `initialize'
When I execute JSON.parse in javascript, this works, but this is not parsing properly in ruby console.
This error can be caused by passing JSON.parse an empty string. Try running request.body.rewind before request.body.read.
Already I have spent a lot time to resolve the issue but not getting the actual reason.
I have a issue during parsing the json, below is the my josn which i am trying to format.
ERROR: 757: unexpected token at '"{\"requestId\":\"2323423432\",\"bids\":\"[ {\\"adId\\":50000001, \\"bidNative\\":100,\\"clickPayload\\":\\"clickPayload-1\\", \\"impressionPayload\\":\\"236|458795|12345\\"}, {\\"adId\\":60000002, \\"bidNative\\":200,\\"clickPayload\\":\\"clickPayload-2\\", \\"impressionPayload\\":\\"236|458795|12345\\"}, {\\"adId\\":60000002, \\"bidNative\\":300,\\"clickPayload\\":\\"clickPayload-3\\", \\"impressionPayload\\":\\"236|458795|12345\\"}]\"}"'
actually wherever it shows 2 slashes there are actually 3, but i dont know why stack overflows editor shows like this.
I have two JSON returns.
One I am able to parse fine
{"login"=>"foo", "id"=>bar,
with
#foobar_collect["login"]
But one I am having issues with
{"items"=>[{"user_id"=>foo, "user_type"=>"bar",
I try
#foobar_collect["items"]["user_id"]
And it gives me an error no implicit conversion of String into Integer
What am I doing wrong?
try
#foobar_collect['items'][0]['user_id']
The reason why your code doesn't work is #foobar_collect['items'] is an array.
#foobar_collect["items"].first["user_id"]