The json is build as followed:
{1 : { "title" : "Mini pork pies with piccalilli", "category" : "meat"}, 2 : {"title" : "apple crumble", "category" : "dessert"}}
First of all, {1 : { "title" : "Mini pork pies with piccalilli", "category" : "meat"}, 2 : {"title" : "apple crumble", "category" : "dessert"}} is not a valid JSON. If you want to work with Apple's frameworks, you first need to make a valid JSON.
One possible form:
{
"1" : {
"title" : "Mini pork pies with piccalilli",
"category" : "meat"
},
"2" : {
"title" : "apple crumble",
"category" : "dessert"
}
}
(In valid JSON, the keys need to be JSON string, no number keys are allowed.)
Another would be:
[
{
"title" : "Mini pork pies with piccalilli",
"category" : "meat"
},
{
"title" : "apple crumble",
"category" : "dessert"
}
]
If you were using the latter form, you would directly get an Array from the JSON. So I assume the first one.
But in any way, if your JSON actually looks like {1 : { "title" : "Mini pork pies with piccalilli", ..., please create a valid JSON first.
Assuming you got the JSON file as my first example, you can write some code to convert it to an Array like this:
let jsonText = """
{
"1" : {
"title" : "Mini pork pies with piccalilli",
"category" : "meat"
},
"2" : {
"title" : "apple crumble",
"category" : "dessert"
}
}
"""
func jsonTextToArray(_ jsonText: String) - [[String: Any]]? {
guard let data = jsonText.data(using: .utf8) else {
print("invalid data")
return nil
}
do {
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: [String: Any]] else {
print("bad format")
return nil
}
return json.sorted {Int($0.key) ?? 0 Int($1.key) ?? 0}
.map {$0.value}
} catch {
print(error)
return nil
}
}
if let array = jsonTextToArray(jsonText) {
print(array)
} else {
print("bad jsonText")
}
//-[["title": Mini pork pies with piccalilli, "category": meat], ["category": dessert, "title": apple crumble]]