Created
October 17, 2016 04:07
-
-
Save taywils/8b05b0188f671d8536500606ce5b8fc4 to your computer and use it in GitHub Desktop.
Swift JSON Minify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
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
These last lines
actually effect key / values, so you want to remove those if you want to use this gist.