// // ExtendedJSON.swift // MongoView // // Created by Shadowfacts on 4/4/20. // Copyright © 2020 Shadowfacts. All rights reserved. // import Foundation import JavaScriptCore import MongoSwift struct ExtendedJSON { private init() {} private static let context: JSContext = { let context = JSContext()! let objectId: @convention(block) (String) -> [String: String] = { (id) in return ["$oid": id] } context.setObject(objectId, forKeyedSubscript: "ObjectId" as NSString) return context }() static func normalize(_ string: String) -> String? { return context.evaluateScript("JSON.stringify(\(string))")?.toString() } private static func fromExtJSON(_ string: String) -> Document? { do { let doc = try Document(fromJSON: string) return doc } catch { print("Unable to create document from extended JSON: \(error)") return nil } } static func toDocument(_ string: String) -> Document? { guard let normalized = normalize(string), let doc = fromExtJSON(normalized) else { return nil } return doc } static func prettify(_ string: String) -> String? { let command = "JSON.stringify(JSON.parse(`\(string)`), null, 4)" return context.evaluateScript(command)?.toString() } }