Can't access json object which is array inside json object
i want to access data from json object which have array inside array
and that json file is also uploaded
so pls can anyone check and help me how to get "weather.description"
data
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
let newValue = jsonResult as! NSDictionary
print(jsonResult)
let name = newValue["name"]
//Here i am getting name as variable value
//this is not working
let description = newValue["weather"]??[0]["description"]
//this is not working
let description = newValue["weather"]!![0]["description"]
print()
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()
}
I have edited your code a bit, and added a few comments. Basiclly, lets check for the types of your response structure, and get the desired value.
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
// I would not recommend to use NSDictionary, try using Swift types instead
guard let newValue = jsonResult as? [String: Any] else {
print("invalid format")
return
}
// Check for the weather parameter as an array of dictionaries and than excess the first array's description
if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
print(description)
}
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()
Related
I have been struggling with this for a while and just need some quick help with this basic question.
let url = URL(string: "https://api.coindesk.com/v1/bpi/currentprice.json")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("Error!")
}
else
{
if let content = data
{
do
{
// Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let rates = myJson["bpi"] as? NSDictionary
{
if let currency = rates["USD"] as NSDictionary
{
if let money = currency["rate"]
{
print(money)
}
}
}
}
catch
{
}
}
}
}
task.resume()
self.label.text = (self.money as String?)
I am trying to pass the numerical value for "money" to a label in my view controller.
The main issue is that you are trying to update the label from outside the completion handler of your asynchronous network request. However, there are several other issues with your code. You shouldn't use NSDictionary in Swift, use [String:Any] when parsing JSON dictionaries. .mutableContainers also doesn't have any effect in Swift. Also make sure that you dispatch any UI related updates to the main thread.
let url = URL(string: "https://api.coindesk.com/v1/bpi/currentprice.json")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else {
print(error!); return
}
do {
if let myJson = try JSONSerialization.jsonObject(with: content) as? [String:Any],
let rates = myJson["bpi"] as? [String:Any],
let currency = rates["USD"] as? [String:Any],
let money = currency["rate"] as? String {
DispatchQueue.main.async{
self.label.text = money
}
}
} catch{
print(error)
}
}
task.resume()
Iam getting an error while i try to send the POST request in swift 3. Any one please suggest me the correct syntax for URLSession.shared method in swift 3. this is what i tried. iam new here.
let task = URLSession.shared.dataTask(with: request, completionHandler: {
(data, response, error) in
if error != nil{
print("error");
return
}
do{
let myjson = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parsejson = myjson{
var msg: String!
msg = parsejson["message"] as! String?
print(msg)
}catch error {
print ("")
}
}
})
task.resume().
Here's working URLSession.shared code. I don't have your URL so I used one that is online, free, and produces JSON:
let someURL = URL(string:"https://jsonplaceholder.typicode.com/posts/2")!
let request = URLRequest(url: someURL)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("error")
return
}
guard let data = data else {
print("No data")
return
}
do {
if let myjson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? Dictionary<String,Any> {
if let title = myjson["title"] {
print("Title was \"\(title)\"")
}
}
} catch {
print("Error parsing JSON: \(error)")
}
}
task.resume()
This outputs Title was "qui est esse" for me.
I tried to get the location from the below JSON, but it returns response nil, can you check it once. Below URL gives the response, but I want to display location from below JSON.
let url = URL(string: "http://beta.json-generator.com/api/json/get/4ytNy-Nv7")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
let val = myJson["Location"] as? NSDictionary
print("val=\(val)")
}
catch
{
}
}
}
}
task.resume()
Don't use Foundation datatypes, such as NSDictionary, when they have native Swift counterparts. You also need to cast the JSON to an array of dictionaries. However, the problem that actually caused the issue was that Location is a String and not a dictionary.
guard let myJsonArray = try JSONSerialization.jsonObject(with: content) as? [[String:Any]], let myJson = myJsonArray.first else {return}
print(myJson)
let val = myJson["Location"] as? String
print("val=\(val)")
The root object of the JSON is clearly an array of a dictionary not something (AnyObject). The value for key Location is in the first object of the array
if let myJson = try JSONSerialization.jsonObject(with: content) as? [[String:Any]], !myJson.isEmpty { // check also that the array is not empty
print(myJson)
let val = myJson[0] // get first object of the array
let location = val["Location"] as? String ?? "n/a"
print("location = \(location)")
}
You can use the following function to download your data. Further more since your array has only one object, to access multiple locations you can iterate through the array objects
func downloadData(){
let url = URL(string: "http://beta.json-generator.com/api/json/get/4ytNy-Nv7")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content) as? [[String:Any]]
let object = myJson?[0]
if let location = object?["Location"] as? String{
print(location)
}
}
catch
{
}
}
}
}
task.resume()
}
You can change this part :
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
Into :
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyHashable: Any]
Then if your JSON only have one object try this to get the Location :
let obj = myJson[0]
let location = obj["Location"] as? String
print("Location \(location)")
My error should be quite obvious but I can't find it;
I've a global variable initialized a the beginning of my class:
class InscriptionStageViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var lesSemaines = [String]()
I try to populate this array with a distant json file using that function
func getSemainesStages(){
let url = URL(string: "http://www.boisdelacambre.be/ios/json/semaines.json")
let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
let listeSemaines = myJson["semaine"] as! [[String:AnyObject]]
//print(listeSemaines)
for i in 0...listeSemaines.count-1 {
var tabSem = listeSemaines[i]
let intituleSemaine:String = tabSem["intitule"] as! String
//let dateSemaine:String = tabSem["date"] as! String
DispatchQueue.main.sync
{
self.lesSemaines.append(intituleSemaine)
}
}
} catch
{
print("erreur Json")
}
}
}
task.resume()
}
When I call my function in the viewDidLoad and then I print my global array, it's empty (the URL is correct, the json data is read correctly and when I read the data appended in the array in the loop, it print the (so) needed value...)
Thanks in advance
The download takes time. Introduce another methode:
func updateUi() {
print(lesSemaines)
//pickerView.reloadAllComponents()
}
And call it after the download finished:
func getSemainesStages(){
// ... your code
let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
// ... your code
for tabSem in listeSemaines{
guard let intituleSemaine = tabSem["intitule"] as? String else {
print("erreur Json")
continue
}
self.lesSemaines.append(intituleSemaine)
}
// update UI *after* for loop
DispatchQueue.main.async {
updateUi()
}
// ... your code
}
}
I have updated your code to Swift 3. Please replace it with below code.
func getSemainesStages(){
let url = URL(string: "http://www.boisdelacambre.be/ios/json/semaines.json")
let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
let listeSemaines = myJson["semaine"] as! [[String: Any]]
for i in 0...listeSemaines.count-1 {
var tabSem = listeSemaines[i]
let intituleSemaine:String = tabSem["intitule"] as! String
self.lesSemaines.append(intituleSemaine)
}
print(self.lesSemaines)
} catch {
print("erreur Json")
}
}
}
task.resume()
}
I just started coding in swift and I am at the point that I can get a single value out of the JSON but I can't seem to get all the values out of it by looping trough the array.
so my question is how do I get all the values out and view it as float or string.
here is my code:
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
//print(myJson)
for items in myJson [AnyObject] {
print(items)
}
//here is the single value part, it looks for the rates then it puts it in label.
if let rates = myJson["rates"] as? NSDictionary{
if let currency = rates["AUD"]{
print(currency);
self.label.text=String(describing: currency)
}
}
}
catch
{
}
}
}
}
task.resume()
Try this code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.getJson()
}
func getJson(){
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Dic
guard let myJson:[String:Any] = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] else {return}
//print(myJson)
for items in myJson {
print(items)
}
//here is the single value part, it looks for the rates then it puts it in label.
if let rates = myJson["rates"] as? NSDictionary{
if let currency = rates["AUD"]{
print(currency);
// self.label.text=String(describing: currency)
}
}
}
catch
{
}
}
}
}
task.resume()
}
}
And the result in the console is like below:
The myJson is the dictionary what you want.
I strongly recommend that you use SwiftyJSON to deal with JSON. It's extremely easy to learn and use.
first, you should install SwiftyJSON via CocoaPods (or any other way you like). then you can code it simply like below:
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
// Initialization
let myJson = JSON(data: content)
// Getting a string using a path to the element
self.label.text = myJson["rates"]["AUD"].stringValue
// Loop test
for (key,value):(String, JSON) in myJson["rates"] {
print("key is :\(key), Value:\(value.floatValue)")
}
}
}
}
task.resume()
try this out:
if let currency = rates["AUD"] as? NSDictionary{
for(key,value) in currency {
// the key will be your currency format and value would be your currency value
}
}