0

From this,

{
  “students”: [
    {
      “name”: “test1”,
      "id": 1,
      "created_at": "2019-03-13T21:34:30Z",
      "updated_at": "2019-03-13T21:34:30Z",
      “title”: "My test ticket2",
      "description": “My test description!”
     }
  ],
  "count": 1
}

How can I get the value of id, description and count? I did:

JSON.parse(response)

but I am not sure how to get the value.

2 Answers 2

2

You need to parse twice, if you just parse once you will get the error: TypeError: no implicit conversion of Hash into String

you should do like that:

parsed_response = JSON.parse(response.to_json)

Then you can get the values as you need:

parsed_response['students'][0]['id']

You can also use the dig method if your ruby version is higher than 2.3:

parsed_response.dig('students', 0, 'id')
=> 1
Sign up to request clarification or add additional context in comments.

Comments

1

JSON.parse returns hash.

Fetching information about student:

parsed_response = JSON.parse(response)
parsed_response['students'].first['id']
parsed_response['students'].first['name']
parsed_response['students'].first['description']

If you have more than one values, iterate over them with each.

Fetching count:

parsed_response = JSON.parse(response)
parsed_response['count']

Instead of [] you can use fetch (parsed_response.fetch('students')). Please keep in mind, that fetch raises an error when the key is missing.

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.