Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

ios

swift3

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")
like image 324
roy Avatar asked Oct 23 '25 18:10

roy


2 Answers

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")
like image 122
vadian Avatar answered Oct 26 '25 07:10

vadian


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.

like image 34
Vyacheslav Avatar answered Oct 26 '25 08:10

Vyacheslav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!