I want to handle JSON::ParserError

Asked 2 years ago, Updated 2 years ago, 72 views

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

2022-09-30 14:57

3 Answers

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.


2022-09-30 14:57

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'}


2022-09-30 14:57

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

JSON Perth Failure Screen


2022-09-30 14:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.