I am new to Swift and iOS development and I am currently learning how to work with JSON data.
I am trying to parse nested JSON data and display the following output:
White hex value is #ffffff
Black hex value is #000000
Gray10 hex value is #f5f7f8
Gray20 hex value is #e8eced
Gray30 hex value is #d5d9db
Gray40 hex value is #b6bec2
Gray50 hex value is #8e999e
Gray60 hex value is #69757a
Gray70 hex value is #495257
Gray80 hex value is #333a3d
Gray90 hex value is #1f2426
Purple10 hex value is #ffc7f2
Purple20 hex value is #f59de2
Purple30 hex value is #e07ecb
Purple40 hex value is #d160b7
Purple50 hex value is #b34fa0
Purple60 hex value is #964286
Purple70 hex value is #773569
Purple80 hex value is #5b284f
Purple90 hex value is #401c36
I am able to parse a simple JSON file such as this:
{
"color": {
"white": { "value": "#fff" },
"black": { "value": "#000" }
}
}
However, I cannot figure out how to correctly decode the nested data (seen below) into structs and concatenate the gray and purple keys with their numeric intensity keys (10-90) as seen in the desired output above.
Here is my playground code with nested JSON data that is not working:
import Foundation
let json = """
{
"color": {
"white": { "value": "#fff" },
"black": { "value": "#000" },
"gray": {
"10": { "value": "#f5f7f8" },
"20": { "value": "#e8eced" },
"30": { "value": "#d5d9db" },
"40": { "value": "#b6bec2" },
"50": { "value": "#8e999e" },
"60": { "value": "#69757a" },
"70": { "value": "#495257" },
"80": { "value": "#333a3d" },
"90": { "value": "#1f2426" }
},
"purple": {
"10": { "value": "#ffc7f2" },
"20": { "value": "#f59de2" },
"30": { "value": "#e07ecb" },
"40": { "value": "#d160b7" },
"50": { "value": "#b34fa0" },
"60": { "value": "#964286" },
"70": { "value": "#773569" },
"80": { "value": "#5b284f" },
"90": { "value": "#401c36" }
}
}
}
""".data(using: .utf8)!
struct color: Codable {
let value: String
struct intensity {
let value: String
}
}
struct Entry: Codable {
let color: [String: color]
}
let jsonDecoder = JSONDecoder()
do {
let parsedJSON = try jsonDecoder.decode(Entry.self, from: json)
for color in parsedJSON.color {
print("\(color.key) hex value is \(color.value.value)")
}
}
Ultimately this functionality will end up in an iOS app.
The (partial) JSON data shown in the code above is actual production data. It is being provided to me in that format. So I am unable to change how the JSON data is defined or nested.
I would appreciate some guidance on how to parse nested JSON data and display the data as shown above.