Wednesday, July 9, 2014

Parse JSON in Ruby in 10 simple steps

1. Get a JSON Endpoint. You know you want one.

2. Map the JSON file by running your RUBY Interpreter (like pry or erb) and requiring the gems "awesome_print" & "HTTParty" in order to see the JSON file structure. Try your HTTParty.get() request without the awesome_print if you don't believe me, you will return data but it won't be easy to read.

3. In your Ruby Interpreter uri = "https://data.cityofnewyork.us/api/views/he7q-3hwy/rows.json"

4. parsed = HTTParty.get(uri). Congratulations you have a human readable JSON file now.

5. now type 'parsed.keys' In order to find the top level areas of your file. In this case you get "meta" & "data"... and a lot of other json stuff. 'Meta' is just crap and 'data' is what holds the actual valuable information.

6. Continue the pattern by typing in 'parsed["data"].keys' which returns a failure message telling you its an array, bingo! Do you like being careful? Type 'parsed['data'].class to make sure what kind of data you are dealing with at first.

7. type 'parsed["data"].length', which returns a lot of info in there. It must be valuable, eh? Proove it!

8. Lets check one at random. Type 'parsed["data"].sample'

9. Lets check the one at index [0]. Type 'parsed["data"][0]'. You see a bunch of stuff don't you? Some of it is garbage, some seems rather valuable, but all are separated by commas. Do you remember how to count? Good, 'parsed["data"].sample[0]' returns the first entry, but in this case that is probably just the ID, what we really want is entry [9] & [10], the 10th and 11th entries in each Array. 10. Too lazy to count? Good, let's use rubys each_with_index method in order to take each value and assign it an number, like so:

parsed["data"].sample.each_with_index {|value, index| puts "#{index}: #{value} " }

Monday, July 7, 2014

MongoDB Intro

db.cars.remove( {"_id" : allCars[3]["_id"]} ) db.cars.find() db.cars.update( {"_id" : allCars[2]["_id"]}, {$set : { "dog_friendliness" : true } } ) db.cars.find() "_id" "make" "name" "color" db.cars.insert({ "make" : "Nissan", "name" : "Leaf", "color: "Yellow" }) //new car is made db.cars.find( { "make" : "Nissan", "dog_friendliness" : true }