0

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?

2 Answers 2

1

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 }]
Sign up to request clarification or add additional context in comments.

3 Comments

Note: This is rails/active_support only.
Thanks! This is exactly what I needed. I was looking in the Ruby docs instead of Rails docs, hence why I missed the method.
Look at the other extensions in active support too. They contain a lot of useful things that are good to know about.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.