added more extension methods

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2022-07-13 10:26:09 -05:00
parent a7d6fff40e
commit 863a9fbbe5

View File

@ -145,17 +145,55 @@ extension JSONValue: ExpressibleByDictionaryLiteral {
}
}
extension Dictionary where Key == String, Value == Any {
public func toJSONValue() throws -> [String: JSONValue] {
extension Array where Element == Any {
public func toJSONValue() throws -> JSONValue {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return try JSONDecoder().decode([String:JSONValue].self, from: data)
return try JSONDecoder().decode(JSONValue.self, from: data)
}
}
extension Array where Element == AnyHashable {
public func toJSONValue() throws -> JSONValue {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return try JSONDecoder().decode(JSONValue.self, from: data)
}
}
extension Array where Element == JSONValue {
public func toJSONArray() throws -> [Any] {
let encoded = try JSONEncoder().encode(self)
guard let json = try JSONSerialization.jsonObject(with: encoded, options: .mutableContainers) as? [Any] else {
throw JSONValueError.encode
}
return json
}
}
extension Dictionary where Key == String, Value == Any {
public func toJSONValue() throws -> JSONValue {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return try JSONDecoder().decode(JSONValue.self, from: data)
}
}
extension Dictionary where Key == String, Value == AnyHashable {
public func toJSONValue() throws -> [String: JSONValue] {
public func toJSONValue() throws -> JSONValue {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return try JSONDecoder().decode([String:JSONValue].self, from: data)
return try JSONDecoder().decode(JSONValue.self, from: data)
}
}
extension Dictionary where Key == String, Value == Any {
public func toJSONValueDictionary() throws -> JSONValueDictionary {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return try JSONDecoder().decode(JSONValueDictionary.self, from: data)
}
}
extension Dictionary where Key == String, Value == AnyHashable {
public func toJSONValueDictionary() throws -> JSONValueDictionary {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return try JSONDecoder().decode(JSONValueDictionary.self, from: data)
}
}