I'm creating a website with rails.
Among them is the process of parsing JSON.
I'm saying this very well, but if you intentionally give me a strange character, I get JSON::ParserError
and I get an error screen.
I'd like to write something like "This is what I do in case of a perspective error", but how can I do it?
ruby-on-rails ruby json
Use resque
to catch exceptions in Ruby (for example, JSON::ParserError
.
require "json"
json='{"fate":"testarossa'
begin
hash=JSON.parse(json)
hash
rescue JSON::ParserError=>e
$stderr.puts "ERROR:#{e}"
end
For resque
, see http://docs.ruby-lang.org/ja/2.1.0/doc/spec=2fcontrol.html#begin.
I have already given you a basic answer, but I would like to give you an example of a possible additional solution.
require 'json'
s='{"abc":"aaa"'
s2 = '{"abc":"aaa"}'
t=JSON.parse(s)rescunil#t is substituted by nil
t=JSON.parse(s2)rescunil#t is substituted by {abc:'aaa'}
When I create a website and give strange characters, does it mean that I want to enter text in JSON format on the form and process the error?
In scaffold, for example, you created a model similar to the following:
rails gscaffold JsonArticle body:text
In that case, you can add the following validation to app/models/json_article.rb
to display an error when filling out the form.
class JsonArticle<ActiveRecord::Base
values_each —body do | r, a, v |
json = JSON.parse vrescunil
r.errors.adda, "JSON format is incorrect" if json.nil?
end
end
916 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
620 Uncaught (inpromise) Error on Electron: An object could not be cloned
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.