I am having trouble creating a JSON object that embeds an array of dictionaries. Here is non-working code of what I want to do. The myMessages in parameters throws an error:
let myMessages: [Dictionary: Any?] = [
{ role: "system", content: "You’re a social media manager writing Instagram captions." },
{ role: "user", content: "I want to post something on Instagram on Mother’s day. Brainstorm some ideas." },
]
let parameters: [String: Any?] = [
"model": model,
"messages": myMessages,
]
guard let parametersJson = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {
return
}
Edit:
I can get it to compile and run if I change myMessages to a dict as follows but the API requires an array.
var myMessages = ["role": "user", "content": "How many days in a week"]
2
Answers
The declaration of your
myMessages
variable isn’t valid Swift:The type doesn’t make sense. It looks like you want an array of dictionaries, but
[Dictionary : Any?]
would give you a dictionary, which would be mapping keys of typeDictionary
(which itself is not valid without generic parameters) toAny?
values. What you probably want is[[String : Any]]
, which would be an array (hence the outer brackets) of dictionaries with String keys (i.e.[String : Any]
).Curly braces are correct to define a dictionary in raw JSON, but not in Swift. Swift uses square brackets for that. Replace the
{
and}
with[
and]
.Your dictionary keys need to be correctly formatted as strings; i.e.
"role":
rather thanrole:
, unless of courserole
is a variable pointing to some string key.Swift dictionaries aren’t spelled with
{ }
(like in say Python or JS). They use[ ]
.You tried that too, but made
myMessages
into just the first dictionary. You can make an array of them: