Reputation: 4783
let data = NSData(contentsOfFile: "myfile")
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonData: NSData! = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var validJson = false
if (NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) != nil) {
validJson = true
}
I want the code above to only set validJson
true when the contents of jsonData is actually valid JSON. At the moment if I pump anything into the "myfile" file which can be seen in the code, validJson
is always true.
How can I fix this so validJson
is only true when it's actually valid JSON?
Upvotes: 11
Views: 14770
Reputation: 69
Using Swift 5 to check if string contains valid JSON:
let string = "{ }"
let data = string.data(using: .utf8)
let isValidJson = (try? JSONSerialization.jsonObject(with: data)) != nil
Upvotes: -1
Reputation: 20786
isValidJSONObject:
Returns a Boolean value that indicates whether a given object can be converted to JSON data.
Code Example
let jsonString = "{}"
let jsonData = jsonString.data(using: String.Encoding.utf8)
if JSONSerialization.isValidJSONObject(jsonData) {
print("Valid Json")
} else {
print("InValid Json")
}
Upvotes: 10
Reputation: 130201
I have tested the following:
let jsonString = ""
let jsonString = "<html></html>"
let jsonString = "{}"
with code:
let jsonData: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var error: NSError? = nil
let validJson = (NSJSONSerialization.JSONObjectWithData(jsonData, options:nil, error: &error) != nil)
println("Valid JSON: \(validJson)")
First two strings print false
, the third prints true
as expected.
I think you are probably loading a different file than you expect.
Upvotes: 3