A
A
Anton2016-05-28 19:54:40
Ruby on Rails
Anton, 2016-05-28 19:54:40

How to find out what was received: JSON or not?

There is a link to JSON. Information on it is parsed in the RoR application.
Sometimes on a remote server, instead of JSON, a 503 error appears, stating that the server is currently unavailable.

url = 'this url'
uri = URI(url)
response = Net::HTTP.get(uri)
data = JSON.parse(response)

How to implement validation? For example, how to check what is received from the server? I want to implement a check for "JSON".
Of course, you can pre-check the status of the response from the server, but maybe there is some other option provided in Ruby / RoR in conjunction with the JSON class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Agaltsov, 2016-05-28
@hummingbird

Yes, in general, just a status check is intended to verify information.
usually it is written, if the status is 200, then we start parsing JSON.

A
Andrey Andreev, 2016-05-28
@b0nn1e

def valid_json?(json)
  begin
    JSON.parse(json)
    return true
  rescue JSON::ParserError => e
    return false
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question