json_repair_ios is a small Swift package for repairing malformed JSON commonly produced by LLMs before decoding it on Apple platforms.
It is inspired by the MIT-licensed Python project mangiucugna/json_repair, with a native Swift implementation and no runtime dependencies.
- Missing quotes around object keys and bare string values
- Single-quoted strings and curly quotes
- Trailing commas and missing commas between object members
- Truncated
true,false, andnullliterals - JavaScript/Python-style booleans and nulls (
True,False,None) - Line comments, block comments, and
#comments - Markdown fenced JSON blocks and JSONP wrappers
- Stray ellipsis entries in arrays
- Unclosed arrays, objects, and strings when a valid repair is possible
This package is intentionally heuristic. It is designed as a fallback for model output, not as a replacement for strict validation of trusted protocols.
Add the package with Swift Package Manager:
.package(url: "https://github.com/GP-Moon/json_repair_ios.git", branch: "main")Then add the product:
.product(name: "JSONRepairIOS", package: "json_repair_ios")import JSONRepairIOS
let badJSON = #"{"users":[{"name":"Ada","role":"admin",}],"ok":tru"#
let repaired = try JSONRepair.repair(badJSON)
// {"users":[{"name":"Ada","role":"admin"}],"ok":true}Decode directly into a Decodable type:
struct Payload: Decodable {
let name: String
let enabled: Bool
}
let payload = try JSONRepair.decode(Payload.self, from: "{name: 'Pokebot', enabled: True}")Inspect the repaired value without serializing:
let value = try JSONRepair.loads("{items: [1, 2, false]}")JSONRepair.repair(_:options:) -> StringJSONRepair.loads(_:options:) -> JSONValueJSONRepair.decode(_:from:options:decoder:) -> Decodable
JSONRepairOptions supports:
skipValidation: skip the strictJSONSerializationfast path and go straight to repair.prettyPrinted: emit formatted JSON.sortKeys: serialize object keys alphabetically.
- Swift 5.9+
- iOS 17+
- macOS 14+
swift build
swift testMIT. See LICENSE.