Skip to content

Instantly share code, notes, and snippets.

@wafflespeanut
Last active October 9, 2018 13:20
Show Gist options
  • Save wafflespeanut/1d94d15ff4b77ca8abd64d8b97bd91f4 to your computer and use it in GitHub Desktop.
Save wafflespeanut/1d94d15ff4b77ca8abd64d8b97bd91f4 to your computer and use it in GitHub Desktop.
DSV to JSON converter (Swift)
import Foundation
var args = CommandLine.arguments
let name = args.removeFirst()
func printUsage() {
print(
"Usage: \(name) [FILE] -d DELIM [-o OUT_FILE]"
)
}
guard let filePath = args.first else {
printUsage()
print("Input file required.")
exit(1)
}
guard var i = args.firstIndex(of: "-d"), args.count - 1 > i else {
printUsage()
print("Expected delimiter")
exit(1)
}
var delimiter = args[i + 1]
var nameComponents = filePath.components(separatedBy: ".")
nameComponents[nameComponents.count - 1] = "json"
var outFilePath = nameComponents.joined(separator: ".")
if let i = args.firstIndex(of: "-o"), args.count - 1 > i {
outFilePath = args[i + 1]
}
if delimiter == "\\t" {
delimiter = "\t"
}
var columns = [String: [String]]()
let contents: String
do {
contents = try String(contentsOfFile: filePath, encoding: .utf8)
} catch let error {
print("Error reading file \(filePath): \(error)")
exit(1)
}
let lines = contents.components(separatedBy: .newlines)
guard let firstLine = lines.first else {
print("Missing keys in DSV file.")
exit(1)
}
let keys = firstLine.components(separatedBy: delimiter)
keys.forEach { word in
columns[word] = []
}
for (i, line) in lines.dropFirst().enumerated() {
let values = line.components(separatedBy: delimiter)
if values.count < keys.count {
print("Skipping line \(i + 2) because it has \(values.count) values for \(keys.count) keys")
}
for (key, value) in zip(keys, values) {
columns[key]!.append(value)
}
}
if let data = try? JSONEncoder().encode(columns) {
let url = URL(fileURLWithPath: outFilePath)
do {
try data.write(to: url)
} catch let err {
print("Cannot write to \(outFilePath): \(err)")
}
} else {
print("Cannot encode JSON data.")
exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment