How to parse JSON when there is no key but only integer / string value?
How can I parse this JSON file? My code works when both keys and values ββare available.
My code:
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")
source to share
If the root JSON object is not a dictionary or an array, you need to pass .allowFragments
as an option (btw. Never pass .mutableContainers
, this is pointless 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")
source to share
THIS ANSWER IS NOT CORRECT. POSSIBLE FOR PARSE Int etc., for example in an article in vadian magazine
This is not a json object format specification. JSON data must start with "{" for an object or "[" for an array of elements.
So, if you have different formats, I would suggest the following:
Check the first letter. if "{" parse as object.
Check the first letter. if "[" parse as an array.
Otherwise:
Just convert String to Int with something like this:
var num = Int("339")
If you don't use a simple string.
source to share