Babar
Babar

Reputation: 1202

JSON responses in Rails

I am using an API for my university project, which sends me multiple responses which are all valid JSON.

Both are treated as string in response.body so I need to parse them into JSON or ruby object.

The first one passes through the JSON parser but fails if I use eval which returns a ruby object

{
  apiCode: "SUCCESS",
  friendlyMessage: "All information saved successfully"
}

Second one passes through eval and gives me a valid Ruby object but fails as a valid JSON.

{
  apiCode: "SUCCESS_WITH_ERRORS",
  friendlyMessage: "Some of the information was not processed",
  successfulIds: [
  {
    ssid: "My Test 1",
    bssid: "2d:8c:e5:5c:bb:b9"
  },
  {
    ssid: "My Test 2",
    bssid: "2a:7d:a4:5c:aa:a7"
  } 
  ]

Regards,

Babar

Upvotes: 1

Views: 95

Answers (2)

Vasfed
Vasfed

Reputation: 18444

Using eval for parsing data coming from some external source is a bad idea, because opens a direct code execution vulnerability.

For parsing JSON there's a build-in parser:

require 'json'
ruby_object = JSON.load(your_json_string)

For more speed, if you need it, use a dedicated json parser gem like oj directly or through MultiJson gem.

Also your second json is missing the final } so is not valid, also hash keys in json are supposed to be in "

Upvotes: 1

Umang Raghuvanshi
Umang Raghuvanshi

Reputation: 1258

Running both your JSON blobs through both JSON Lint and Ruby's JSON library results in an error.

The error for the first one is

Error: Parse error on line 1:
{   apiCode: "SUCCESS",
--^
Expecting 'STRING', '}', got 'undefined'

and for the second one is

Error: Parse error on line 1:
{   apiCode: "SUCCESS_WI
--^
Expecting 'STRING', '}', got 'undefined'

The errors suggest that your JSON should look like (I'm showing the first one here)

{
  "apiCode": "SUCCESS",
  "friendlyMessage": "All information saved successfully"
}

(which parses successfully everywhere).

Upvotes: 1

Related Questions