-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sanitize dictionaries before serialization (#82)
- Loading branch information
1 parent
6c8d69d
commit 67c923e
Showing
6 changed files
with
75 additions
and
65 deletions.
There are no files selected for viewing
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
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
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
This file was deleted.
Oops, something went wrong.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// | ||
// DictUtils.swift | ||
// PostHog | ||
// | ||
// Created by Manoel Aranda Neto on 27.10.23. | ||
// | ||
|
||
import Foundation | ||
|
||
public func sanitizeDicionary(_ dict: [String: Any]?) -> [String: Any]? { | ||
if dict == nil || dict!.isEmpty { | ||
return nil | ||
} | ||
|
||
var newDict = dict! | ||
|
||
for (key, value) in newDict where !isValidObject(value) { | ||
if value is URL { | ||
newDict[key] = (value as! URL).absoluteString | ||
continue | ||
} | ||
if value is Date { | ||
newDict[key] = ISO8601DateFormatter().string(from: (value as! Date)) | ||
continue | ||
} | ||
|
||
newDict.removeValue(forKey: key) | ||
hedgeLog("property: \(key) isn't serializable, dropping the item") | ||
} | ||
|
||
return newDict | ||
} | ||
|
||
private func isValidObject(_ object: Any) -> Bool { | ||
if object is String || object is Bool || object is any Numeric || object is NSNumber { | ||
return true | ||
} | ||
if object is [Any?] || object is [String: Any?] { | ||
return JSONSerialization.isValidJSONObject(object) | ||
} | ||
// workaround [object] since isValidJSONObject only accepts an Array or Dict | ||
return JSONSerialization.isValidJSONObject([object]) | ||
} |
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