skip to Main Content

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


  1. The declaration of your myMessages variable isn’t valid Swift:

    1. 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 type Dictionary (which itself is not valid without generic parameters) to Any? 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]).

    2. 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 ].

    3. Your dictionary keys need to be correctly formatted as strings; i.e. "role": rather than role:, unless of course role is a variable pointing to some string key.

    Login or Signup to reply.
  2. 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:

    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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search