Swift: checking if a String is valid JSON


I’ve been developing an application that produces a JSON string for use online. Pretty simple, but I want to make sure the JSON is valid (since a user can edit the JSON by hand if they want to before using the JSON string). How can you quickly validate your JSON?

let jsonString = composedString
if let jsonDataToVerify = jsonString.data(using: String.Encoding.utf8)
    do {
        _ = try JSONSerialization.jsonObject(with: jsonDataToVerify)
        print("JSON is valid.")
    } catch {
        print("Error deserializing JSON: \(error.localizedDescription)")

Pretty easy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.