-2

i have the following Json

USD {
    "avg_12h" = "8252.96";
    "avg_1h" = "8420.80";
    "avg_24h" = "8253.11";
    "avg_6h" = "8250.76";
    rates =     {
        last = "8635.50";
    };
    "volume_btc" = "76.05988903";
}

where USD is a key found after searching in a json file, i want to access "avg_12h" value and assign it to a variable, what is the best way to do it.


import UIKit

/*URLSessionConfiguration.default
URLSessionConfiguration.ephemeral
URLSessionConfiguration.background(withIdentifier: <#T##String#>)

// create a URLSession instance
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)*/

/*create a URLSession instance*/
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
/*
The session.dataTask(with: url) method will perform a GET request to the url specified and its completion block
 ({ data, response, error in }) will be executed once response is received from the server.*/
let url = URL(string: "https://localbitcoins.com/bitcoinaverage/ticker-all-currencies")!
let task = session.dataTask(with: url) { data, response, error in

    // ensure there is no error for this HTTP response
    guard error == nil else {
        print ("error: \(error!)")
        return
    }

    // ensure there is data returned from this HTTP response
    guard let content = data else {
        print("No data")
        return
    }
    /*JSONSerialization.jsonObject(with: content,
     options: JSONSerialization.ReadingOptions.mutableContainers) as?
     [String: Any] will parse the JSON data returned from web server into a dictionary*/
    // serialise the data / NSData object into Dictionary [String : Any]
    guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
        print("Not containing JSON")
        return
    }
    let bolivares = "VES"
    for (key, value) in json {
        if key==bolivares {
           print(value)
        //ADD CODE TO ACCESS avg_12h and assign it to a value
                }
            }
        }
    // update UI using the response here
// execute the HTTP request
task.resume()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • https://stackoverflow.com/questions/24013410/how-to-parse-a-json-file-in-swift – Akshay Oct 25 '19 at 19:02
  • 3
    Possible duplicate of [How to parse a JSON file in swift?](https://stackoverflow.com/questions/24013410/how-to-parse-a-json-file-in-swift) – dustinos3 Oct 25 '19 at 19:47

3 Answers3

0

Assuming you are receiving the JSON as raw data and it hasn't been converted to an object yet, ou would want to do something like the following:

guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:[String]] else { return }
let usd = jsonObject["USD"]
let avg_12h = usd["avg_12h"]

But this will only work based on some assumptions I've made about the JSON you've provided. Is there a way you can link to a paste of the full JSON file?

David Chopin
  • 2,780
  • 2
  • 19
  • 40
  • guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else { print("Not containing JSON") return } let bolivares = "VES" for (key, value) in json { if key==bolivares { print(value) //ADD CODE TO ACCESS avg_12h and assign it to a value } } } // update UI using the response here // execute the HTTP request – Tarek TTG Oct 25 '19 at 19:45
  • sorry for the mess, i did that cast it as a String: Any, but i cant access the avg_12h – Tarek TTG Oct 25 '19 at 19:46
  • Thanks for the comment, tried that, but cannot access it directly, tried casting a new object did not work. – Tarek TTG Oct 25 '19 at 20:11
  • Any ideas on how to access the avg_12h and the rates? or any other value within the JSON object – Tarek TTG Oct 26 '19 at 17:46
0

Create two simple structs to hold your data (I didn't add all fields here)

struct PriceInfo {
    let avg12h: String
    let avg1h: String
    let rates: [Rate]
}

struct Rate {
    let last: String
}

then after converting json you can map it to a dictionary of [String: PriceInfo] where the key is the currency code

do {
    if let json = try JSONSerialization.jsonObject(with: content) as? [String: Any] {
        let prices: [String: PriceInfo] = json.mapValues {
            let dict = $0 as? [String: Any]
            let avg12h = dict?["avg_12h"] as? String ?? ""
            let avg1h = dict?["avg_1h"] as? String ?? ""
            let rates = dict?["rates"] as? [String: String] ?? [:]
            return PriceInfo(avg12h: avg12h, avg1h: avg1h, rates: rates.compactMap { rate in Rate(last: rate.value) } )
        }
    }
} catch {
    print(error)
    return
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
-2

Try to use CodingKey, it will be more clearer and JSONDecoder().decode method. I assume that you use any JsonViewer

motivated
  • 53
  • 8