Reputation: 391
I have an invalid JSON coming from external API:
{
status: 'ok',
pills: [{
id: 1,
name: "Мезим форте",
img: "https://cloud.fdoctor.ru/test_task/static/mezim.jpg",
desription: "Перед завтраком",
dose: "По таблетке"
},
{
id: 2,
name: "Bioderma",
img: "https://cloud.fdoctor.ru/test_task/static/bioderma.jpg",
desription: "Во время еды"
dose: "По 3 глотка"
},
{
id: 3,
name: "Гексорал, Аэрозоль"
img: "https://cloud.fdoctor.ru/test_task/static/gecsoral.jpg",
desription: "При острых болях"
dose: "По 3 пшика"
},
{
id: 4,
name: "Тантум Верде, спрей"
img: "https://cloud.fdoctor.ru/test_task/static/tantum.jpg",
desription: "Каждые 4 часа в течении 7 дней"
dose: "По таблетке"
}
]
}
Is there a way to parse it with codable protocol?
Fixing it on API is not an option.
Upvotes: 0
Views: 318
Reputation: 52043
You can use the following reg ex replacements to clean the string and make it json compliant
//Surround keys with quotes
let firstStep = input.replacingOccurrences(of: #"\s(\w+):{1}"#,
with: #""$1":"#,
options: .regularExpression)
//Fix status value
let json = firstStep.replacingOccurrences(of: "'", with: "\"")
Upvotes: 0