mztwo
mztwo

Reputation: 365

Parsing JSON hash with each generates "can't convert String into Integer"

I am parsing JSON from an API with the following code:

def json_test
    content = open("API URL").read  
    json = JSON.parse(content)
    json.each do |a|
        puts a["first_name"]
    end
end

The reason I'm using each is because the API request will return an array of hashes for multiple users, like this:

[{
  "id": "1",
  "first_name": "John"
},
{
  "id": "2",
  "first_name": "Bob"
}]

However, the API will return just a hash if the request only returns a single user, like thus:

{
  "id": "2",
  "first_name": "Bob"
}

This is where I'm getting the error message: can't convert String into Integer (TypeError)

I've been searching for a good way to be able to parse when it's not returning an array but just a hash and I'm stumped. Any pointers?

Upvotes: 0

Views: 1491

Answers (2)

mechanicalfish
mechanicalfish

Reputation: 12826

Array.wrap is designed just for this purpose.

Wraps its argument in an array unless it is already an array (or array-like).

Array.wrap({ a: 1 }) # => [{ a: 1 }]
Array.wrap [{ a: 1 }, { b: 2 }] # => [{ a: 1 }, { b: 2 }]

Upvotes: 1

Guilherme Bernal
Guilherme Bernal

Reputation: 8293

One way is putting it all inside a single element array and flattening it:

json = [JSON.parse(content)].flatten

If it is not an array, the flatten will be noop. If it is, the extra array layer will be removed.

Upvotes: 0

Related Questions