Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Last active Jan 25, 2021
Embed
What would you like to do?
Decoding JSON with endless nesting
import Foundation
let JSON = """
[{
"sub_elements": [{
"sub_elements": [{
"id": "4315FAC2-0809-478C-BED8-54F28B0A9A57",
"name": "Shape 1"
}, {
"id": "D2985D5B-B98A-4549-A4ED-3742583A2532",
"name": "Image 1"
}, {
"sub_elements": [{
"id": "718F235A-E2FB-4A05-A2A9-198CFA6B135A",
"name": "Shape 2"
}, {
"id": "0C232502-A0D6-4BC7-B4DD-178B0BFE8BB0",
"name": "Image 2"
}],
"id": "C67F6AE9-2EA5-4850-AA00-2A1DB8EB4167",
"name": "Group 3"
}],
"id": "4412C2FA-47D3-4524-A054-F06AE843DA45",
"name": "Group 2"
}, {
"id": "99BBAA31-0A9D-46F8-89C7-BD7EE444919E",
"name": "Shape"
}, {
"id": "B5281F95-72A4-4973-9A70-18ABF1D3DD92",
"name": "Image"
}],
"id": "6ECF5DA1-0558-436C-93E7-CCED4461866D",
"name": "Group"
}]
"""
struct Object: Decodable {
let subElements: [Object]?
let id: String
let name: String
enum CodingKeys: String, CodingKey {
case id, name
case subElements = "sub_elements"
}
}
let jsonData = JSON.data(using: .utf8)!
let objectWithEndlessNesting = try! JSONDecoder().decode([Object].self, from: jsonData)
func showElements(data: [Object], delimeter: String = "") {
var newLevelDelimeter = delimeter
newLevelDelimeter += "-- "
for item in data {
print("\(newLevelDelimeter) Item \(item.id) \(item.name)")
if let subElements = item.subElements {
showElements(data: subElements, delimeter: newLevelDelimeter)
}
}
}
showElements(data: objectWithEndlessNesting)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment