0

I am trying to print a list of currencies and their symbols from a JSON file that I have locally in the project

guard let path: String = Bundle.main.path(forResource: "Common-Currency", ofType: "json") else {return}
    let url = URL(fileURLWithPath: path)

    do {
        let jsonData = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        print(json)

        guard let jsonArray = json as? [Any] else { return }

        for currency in jsonArray {
            guard let eachCurrency = currency as? [String: Any] else {return}
            guard let currencyName = eachCurrency["code"] else {return}
            guard let currencySymbol = eachCurrency["symbol_native"] else {return}

            print(currencyName)
            print(currencySymbol)
        }
    }
    catch {
        print(error)
    }

This is the current code I have, however when I run it only the print(json) command gets executed, not the other 2 prints. What am I doing wrong?

The json looks something like this:

{

"Currencies" : {
"USD": {
    "symbol": "$",
    "name": "US Dollar",
    "symbol_native": "US$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD",
    "name_plural": "US dollars"
},
"CAD": {
    "symbol": "CA$",
    "name": "Canadian Dollar",
    "symbol_native": "CA$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "CAD",
    "name_plural": "Canadian dollars"
},
"EUR": {
    "symbol": "€",
    "name": "Euro",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR",
    "name_plural": "euros"
},
"AED": {
    "symbol": "AED",
    "name": "United Arab Emirates Dirham",
    "symbol_native": "د.إ.‏",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "AED",
    "name_plural": "UAE dirhams"
},
"AFN": {
    "symbol": "Af",
    "name": "Afghan Afghani",
    "symbol_native": "؋",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "AFN",
    "name_plural": "Afghan Afghanis"
},
3
  • 1
    Please post the beginning of the JSON string. json is most likely a dictionary. And if the file is in the bundle you don't need all guard expressions and optional bindings. Force unwrap all dictionary values. If the code crashes it's a design error. Commented Aug 18, 2017 at 8:33
  • Is json really an array?Could you show it? Commented Aug 18, 2017 at 8:33
  • Ok, I have added it now Commented Aug 18, 2017 at 8:42

1 Answer 1

1

The root object is a dictionary [String:Any]. The currencies are the value for key currencies which is also a dictionary.

You get the currency information with

let url = Bundle.main.url(forResource: "Common-Currency", withExtension: "json")!
do {
    let jsonData = try Data(contentsOf: url)
    let json = try JSONSerialization.jsonObject(with: jsonData) as! [String:Any]
    print(json)

    let currencies = json["Currencies"] as! [String: [String:Any]]

    for (key, currency) in currencies {
        let currencyName = currency["name"] as! String
        let currencySymbol = currency["symbol_native"] as! String

        print(key) // == `code`
        print(currencyName)
        print(currencySymbol)
    }
}
catch {
    print(error)
}

For an alphabetical order you have to get the keys, sort them and get the currency dictionary by key.

        let currencies = json["Currencies"] as! [String: [String:Any]]
        let currencyCodes = currencies.keys.sorted()

        for code in currencyCodes {
            let currency = currencies[code]!
            let currencyName = currency["name"] as! String
            let currencySymbol = currency["symbol_native"] as! String

            print(code)
            print(currencyName)
            print(currencySymbol)
        }
Sign up to request clarification or add additional context in comments.

6 Comments

Sorry, at this line of code : "let currencies = json["currencies"] as! [String: [String:Any]]" I get a Thread 1 EXC_BAD_INSTRUCTION error
The key starts with capital C. I edited the answer.
Thanks, worked like a charm. Also, do you have any idea why it doesn't print in order?
Because a dictionary is unordered by definition. I updated the answer with an ordered solution.
Also, how would I display these results in a table as the variables are not global and can't be used in other methods?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.