Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - check if JSON is valid

Tags:

json

swift

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?

like image 243
jskidd3 Avatar asked Aug 31 '15 21:08

jskidd3


2 Answers

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")
    }

API REFERENCE:

like image 149
Ashok R Avatar answered Sep 25 '22 11:09

Ashok R


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.

like image 42
Sulthan Avatar answered Sep 25 '22 11:09

Sulthan