Skip to content

Instantly share code, notes, and snippets.

@RuiAAPeres
Created May 9, 2016 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RuiAAPeres/19f76903010875e4e88f1bdb787b6412 to your computer and use it in GitHub Desktop.
Save RuiAAPeres/19f76903010875e4e88f1bdb787b6412 to your computer and use it in GitHub Desktop.
Quick & Dirty txt2JSON converter
#!/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