Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active February 11, 2017 05:29
Show Gist options
  • Select an option

  • Save kristopherjohnson/c50f79fb71046825c056e5d2ce088e34 to your computer and use it in GitHub Desktop.

Select an option

Save kristopherjohnson/c50f79fb71046825c056e5d2ce088e34 to your computer and use it in GitHub Desktop.
Reads JSON from standard input and writes pretty-printed JSON to standard output
#!/usr/bin/swift
import Cocoa
let stdin = FileHandle.standardInput
let stdout = FileHandle.standardOutput
let stderr = FileHandle.standardError
do {
let inputData = stdin.readDataToEndOfFile()
let jsonObject = try JSONSerialization.jsonObject(with: inputData,
options: [])
let outputData = try JSONSerialization.data(withJSONObject: jsonObject,
options: [.prettyPrinted])
stdout.write(outputData)
print()
}
catch let error as NSError {
let message = "error: \(error.localizedDescription)\n"
stderr.write(message.data(using: .utf8)!)
}
@kristopherjohnson
Copy link
Author

Save this as a file, do chmod +x prettyjson.swift to make it executable, then you can use it like this:

prettyjson.swift <myuglyjson.json >myprettyjson.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment