Created
May 9, 2016 11:41
-
-
Save RuiAAPeres/19f76903010875e4e88f1bdb787b6412 to your computer and use it in GitHub Desktop.
Quick & Dirty txt2JSON converter
This file contains 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
#!/usr/bin/env xcrun swift | |
import Foundation | |
func buildFullPath(fileName: String) -> String { | |
let cwd = NSFileManager.defaultManager().currentDirectoryPath | |
let urlCwd = NSURL(fileURLWithPath: cwd) | |
if let urlPath = NSURL(string: fileName, relativeToURL: urlCwd) { | |
if let path = urlPath.path { | |
return path | |
} | |
} | |
return "" | |
} | |
func countryStringToJSONDic(country: String) -> [String: String] { | |
let countryInfo = country.componentsSeparatedByString(":") | |
return ["code":countryInfo[0], "name":countryInfo[1]] | |
} | |
func countriesToArrayOfCountries(countries:String) -> [String] { | |
return countries.componentsSeparatedByString("\n") | |
} | |
let fileName = Process.arguments[1] | |
let outputFileName = Process.arguments[2] | |
let fullPath = buildFullPath(fileName) | |
let fileContent = try! NSString(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding) | |
let countries = countriesToArrayOfCountries(fileContent as String).map(countryStringToJSONDic) | |
let jsonData = try! NSJSONSerialization.dataWithJSONObject(countries, options: NSJSONWritingOptions.PrettyPrinted) | |
try! jsonData.writeToFile(buildFullPath(outputFileName), options: [.DataWritingAtomic]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment