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"
},
jsonis most likely a dictionary. And if the file is in the bundle you don't need allguardexpressions and optional bindings. Force unwrap all dictionary values. If the code crashes it's a design error.jsonreally an array?Could you show it?