Skip to content

Instantly share code, notes, and snippets.

@westerlund
Last active December 22, 2015 11:11
Show Gist options
  • Save westerlund/15b34ac4ea9f398ac6ce to your computer and use it in GitHub Desktop.
Save westerlund/15b34ac4ea9f398ac6ce to your computer and use it in GitHub Desktop.
Command line tool to pretty-print piped JSON in Swift
//
// Created by Simon Westerlund on 22/12/15.
// Copyright © 2015 Simon Westerlund. All rights reserved.
//
import Foundation
func main() -> Int32 {
let data = NSFileHandle.fileHandleWithStandardInput().readDataToEndOfFile()
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
if let json = String(data: jsonData, encoding: NSUTF8StringEncoding) {
print(json)
return EXIT_SUCCESS
} else {
return EXIT_FAILURE
}
} catch (let error as NSError) {
print(error.localizedDescription)
return EXIT_FAILURE
}
}
exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment