Skip to content

Instantly share code, notes, and snippets.

@taywils
Created October 17, 2016 04:07
Show Gist options
  • Save taywils/8b05b0188f671d8536500606ce5b8fc4 to your computer and use it in GitHub Desktop.
Save taywils/8b05b0188f671d8536500606ce5b8fc4 to your computer and use it in GitHub Desktop.
Swift JSON Minify
import Foundation
extension String {
public var JSONminify: String {
// http://stackoverflow.com/questions/8913138/
// https://developer.apple.com/reference/foundation/nsregularexpression#//apple_ref/doc/uid/TP40009708-CH1-SW46
let minifyRegex = "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+"
if let regexMinify = try? NSRegularExpression(pattern: minifyRegex, options: .caseInsensitive) {
let modString = regexMinify.stringByReplacingMatches(in: self, options: .withTransparentBounds, range: NSMakeRange(0, self.characters.count), withTemplate: "$1")
return modString
.replacingOccurrences(of: "\n", with: "")
.replacingOccurrences(of: "\t", with: "")
.replacingOccurrences(of: "\r", with: "")
} else {
return self
}
}
}
@scspijker
Copy link

These last lines

            return modString
                .replacingOccurrences(of: "\n", with: "")
                .replacingOccurrences(of: "\t", with: "")
                .replacingOccurrences(of: "\r", with: "")

actually effect key / values, so you want to remove those if you want to use this gist.

@AmitaiB
Copy link

AmitaiB commented Jul 29, 2019

I compressed the last 3 lines into:

// Swift 4.x & 5.x
.replacingOccurrences(of: "[\n\t\r]", with: "", options: .regularExpression, range: startIndex..<endIndex)

@scspijker How does whitespace effect key / values?

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