Accessing JSON "2nd tier" id; Ruby script adjustment

Jump to solution
dis1
Community Explorer

api‌ruby

Thanks to  @jperkins  and the Ruby and the Canvas API Self-paced course at https://learn.canvas.net/courses/2438 ,

I am off and running on scripting calls to API.

I am looking for help from anyone on the following questions, though (and forgive my ignorance if I misuse terms):

I am playing around with getting data.

I would like a list of courses with their term_id and number of students enrolled.

I make the call to this endpoint (with these parameters)

/api/v1/accounts/self/courses?include[]=total_students&include[]=term&per_page=100'

then parse the response to get the termid

data = JSON.parse(response.body)
term = data[0]['term']['id']

then crank it into a csv file with the other course info (one line per course).

My script (attached) works, I just need answers to a few questions to get it to work better

1.  I just played around with the "nested" JSON objects until I ferreted out the termid. (again, sorry, don't know the parlance - Inside the course JSON object , "term" : is a braced comma-separated list of its own parameters...)   

Is there a better / easier way to get to these "second level" ids, names, etc than how I did it above? 

Here is the course response and what I wanted

309075_pastedImage_3.png

2.  If I set the per_page as above (100), then the term_id only updates in my csv every 100 lines based on the first termid in that call.  I think I probably need to move my script around a bit, but I have tried to no avail. If I change the per_page to =1, then it works (as it is updated every call again, but this time there is only one course per call). 

This, of course is slow.

Attached is my script ( from the course, site and token redacted,  annotated by me, so forgive me if I misunderstood the purpose of stuff).

Thanks for any thoughts!

Labels (1)
0 Likes
1 Solution
jsavage2
Community Contributor

Hi  @dis1 ‌,

That looks about right, but data[0] will always be the first element (first course) in the response. If you want the terms fo a particular course, you need to read the term for that course inside the loop, where you get the rest of the course info.

You want courses['term']['id'] for each course, not data[0]['term']['id'] for the response.

View solution in original post