Created
April 2, 2015 14:52
-
-
Save phlipper/f912e0335611fa667e02 to your computer and use it in GitHub Desktop.
TECH603 Day 2 - Working with JSON data from a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"id": "AGO", | |
"name": "Angola", | |
"population": 21471618, | |
"capital": "Luanda", | |
"latitude": -8.81155, | |
"longitude": 13.242, | |
"income_level": "Upper Middle", | |
"high_income": false | |
}, | |
{ | |
"id": "ATG", | |
"name": "Antigua and Barbuda", | |
"population": 89985, | |
"capital": "Saint John's", | |
"latitude": 17.1175, | |
"longitude": -61.8456, | |
"income_level": "High", | |
"high_income": true | |
}, | |
{ | |
"id": "BLR", | |
"name": "Belarus", | |
"population": 9466000, | |
"capital": "Minsk", | |
"latitude": 53.9678, | |
"longitude": 27.5766, | |
"income_level": "Upper Middle", | |
"high_income": false | |
}, | |
{ | |
"id": "CAF", | |
"name": "Central African Republic", | |
"population": 4616417, | |
"capital": "Bangui", | |
"latitude": 5.63056, | |
"longitude": 21.6407, | |
"income_level": "Low", | |
"high_income": false | |
}, | |
{ | |
"id": "CHE", | |
"name": "Switzerland", | |
"population": 8081482, | |
"capital": "Bern", | |
"latitude": 46.948, | |
"longitude": 7.44821, | |
"income_level": "High", | |
"high_income": true | |
} | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# require "./countries" | |
require_relative "countries" | |
# `JSON` is in the Standard Library | |
require "json" | |
puts COUNTRIES.first | |
# puts COUNTRIES.last | |
# puts COUNTRIES.class | |
# `File` is in the Core API | |
countries_text = File.read("countries.json") | |
countries = JSON.parse(countries_text) | |
puts countries.first | |
# did we get the same data from both places? | |
puts countries.first == COUNTRIES.first | |
new_json = JSON.dump(countries) | |
File.open("countries2.json", "w") do |file| | |
file.write new_json | |
end | |
countries2_text = File.read("countries2.json") | |
countries2 = JSON.parse(countries2_text) | |
puts countries2.first | |
puts ((countries2.first == COUNTRIES.first) && (countries2.first == countries.first)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment