Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSON Parser for swim.com workout data
# -*- coding: utf-8 -*-
require 'json'
require 'csv'
JSON_FILE = 'swim_com.json'
CSV_FILE = 'swim_com.csv'
class Workout
attr_accessor :name, :date, :id, :note, :distance, :duration, :achievement, :device, :pace, :url
end
str = File.open(JSON_FILE).read
json = JSON.load(str)
workouts = []
json["result"]["feedList"].each do |log|
data = log["workoutData"]
workout = Workout.new
workout.name = data["workoutName"]
# Translate from msec to sec, and fix misinterpreted JST
workout.date = Time.at(data["workoutDate"] / 1000 - 9 * 60 * 60).strftime('%Y-%m-%d %H:%M:%S')
workout.id = data["workoutId"]
# Remove newline because Excel Mac 2011 can not treat newline character
workout.note = data["workoutNote"] ? data["workoutNote"].gsub("\n", ", ") : nil
workout.distance = data["distance"]
workout.duration = data["duration"]
workout.achievement = data["achievement"]
workout.device = data["device"].nil? ? "manual" : data["device"]["name"]
workout.pace = data["pace"]
workout.url = "http://www.swim.com/workout/#{workout.id}"
workouts << workout
end
CSV.open(CSV_FILE, "wb:Windows-31J", :force_quotes => true) do |csv|
csv << ['Date', 'ID', 'Name', 'Distance (M)', 'Duration (sec)', 'Pace (sec/100M)', 'Achievement', 'Device', 'Note', 'URL']
workouts.each do |w|
csv << [w.date, w.id, w.name, w.distance, w.duration, w.pace, w.achievement, w.device, w.note, w.url]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment