0

I have the following piece of JSON returned to a Ruby RestClient post request:

{"importResults":[{"status":"success","id":"ed2a89538d84eff5b92b5baad1fb5a4e"}]}

I am trying to retrieve the status (success) and the id (ed2a89538d84eff5b92b5baad1fb5a4e).

I tried the following code:

jdoc = JSON.parse(jsonAbove)
status = jdoc.fetch("importResults").fetch("status")

This is giving me back the error TypeError: can't convert String into Integer.

I know it's because there is an array in the response that I'm getting this error but I can't seem to get it right.

0

4 Answers 4

4

As many others have already said, you need first in your request.

status = jdoc.fetch("importResults").first.fetch("status")

It looks like you are new to this. I would suggest using irb to mess around with things. For example, you could type s = jdoc.fetch("importResults") and look at the result. You can then play around with the s variable in the console and see what works. s.first, s.class, s[0] etc.

Sign up to request clarification or add additional context in comments.

Comments

3

You need

status = jdoc.fetch("importResults").first.fetch("status")

Comments

3

Right, so it is an array. Get its first (or another appropriate) element and proceed.

status = jdoc.fetch("importResults").first.fetch("status")
#                                      ^^

1 Comment

Upvoted yours since you were first to answer, though I tried to provide alternate syntax. :)
3

That's because you need to get the first item from the array. Change this:

status = jdoc["importResults"].first["status"]

Alternatively:

status = jdoc["importResults"][0]["status"]

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.