Sudipto Roy
Sudipto Roy

Reputation: 6795

How to parse JSON when there is no key but only an Integer / String value?

How can I parse this JSON file ? My code is working when both keys and values are available .

My code so far :

let url = URL(string: "http://uhunt.felix-halim.net/api/uname2uid/felix_halim")
let task = URLSession.shared.dataTask(with: url!, completionHandler: {
    (data, response, error) in
    print("Task Started")

    if error != nil {
        print("In Error!")
    } else {
        if let content = data {
            do {
                let myJSON =
                    try JSONSerialization.jsonObject(with: content, options: .mutableContainers) as AnyObject
                print(myJSON)
            } catch {
                print("In Catch!")
            }
        }
    }
})
task.resume()
print("Finished")

Upvotes: 4

Views: 1035

Answers (2)

Vyacheslav
Vyacheslav

Reputation: 27211

THIS ANSWER IS NOT CORRECT. IT IS POSSIBLE TO PARSE Int , etc like in vadian post

This is not a json object format specification. JSON data must start with "{" for object or "[" for array of elements.

http://www.json.org/

So, if you have got different formats I would suggest this:

Check the first letter. if "{" parse as object.

Check the first letter. if "[" parse as array.

Otherwise:

Just convert the String into Int something like this:

var num = Int("339")

If not use simple String.

Upvotes: 3

vadian
vadian

Reputation: 285082

If the root object of the JSON is not a dictionary or array you have to pass .allowFragments as option (btw. never pass .mutableContainers, it's meaningless in Swift)

let url = URL(string: "http://uhunt.felix-halim.net/api/uname2uid/felix_halim")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    print("Task Started")

    guard error == nil else {
        print("In Error!", error!)
        return
    }

    do {
        if let myJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Int {
            print(myJSON)
        }
    } catch {
        print("In Catch!", error)
    }

}
task.resume()
print("Finished")

Upvotes: 3

Related Questions