Reading and parsing a JSON object in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2015-06-01 21:06:20 - Graham EllisHere's a series of three new examples, building up from one another, showing the reading of a JSON feed from a remote web site in Ruby, and the analysis and presentation of that data.
The first example - [here] - shows the loading of extra modules to handle reading from the web and the JSON format, and the use of the methods loaded fro those modules. Keycode is:
require 'json'
require 'open-uri'
source = URI.parse("http://www.wellho.net/services/_.json")
fh = source.open
stuff = fh.read
things = JSON.parse(stuff)
and the example goes on to define and call methods to descend into the resultant object and display it.
The second example - [here] - extends that initial example by providing an insetting class to give a flexibility of display.
And the third example - [here] - implements a second insetting class which outputs the structures loaded from JSON in the form of Ruby source code assignment statements or as a tree depending on a command line option. So the results will look like
WomanWithCat:kingston grahamellis$ ./tj3.rb -c | head
timedat = '1433231853'
lookfor = ''
acc :
0 :
when = '0'
where = '106.186.17.xx'
which = '/mouth/1114_PHP-Image-upload-script.html'
1 :
when = '0'
where = '194.187.171.xx'
or
WomanWithCat:kingston grahamellis$ ./tj3.rb s_name | head
s_name['timedat'] = '1433231872'
s_name['lookfor'] = ''
s_name['acc'] :
s_name['acc'][0] :
s_name['acc'][0]['when'] = '1'
s_name['acc'][0]['where'] = '94.197.121.xx'
s_name['acc'][0]['which'] = '/pix/crpavatar.jpg'
s_name['acc'][1] :
s_name['acc'][1]['when'] = '3'
s_name['acc'][1]['where'] = '94.197.121.xx'
The source code for these examples is available through the links above, and the code is modestly commented - if you feel that you need to learn more about how it's done, please take a look at our Ruby Training courses, or if you have a group of delegate please enquire about a tailored course at your offices or at our training centre. There are plenty of other examples to help you learn Ruby on our site - see [here] for a complete module list - but there's nothing like having a tutor explain things to you and help you through the initial concepts to get you started!