#Yet another nested json question

1 messages · Page 1 of 1 (latest)

gloomy kelp
#

I know there have been a few questions on this, but I'm still struggling to get me head around it! Hopefully all these questions can help newcomers in the future 😆
I'm trying to get a single value out of a nested json response - it's a response from the OpenAI chat completions API. I want to get the "content" value from the first (if any) element of the "choices" array of objects. But I'm struggling to come up with an appropriate Dynamic incantation. Any wizards out there?

{
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1677858242,
    "model": "gpt-3.5-turbo-0613",
    "usage": {
        "prompt_tokens": 13,
        "completion_tokens": 7,
        "total_tokens": 20
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "\n\nThis is a test!"
            },
            "logprobs": null,
            "finish_reason": "stop",
            "index": 0
        }
    ]
}
gloomy kelp
#

Making some progress. This seems to get me close:

let content = dynamic.field("content", dynamic.string)
let message = dynamic.field("message", content)
let choices = dynamic.list(of: message)
let decoder = dynamic.field("choices", choices)

json.decode(response.body, decoder)

Which returns a type of:

Result(List(String), json.DecodeError)

I'm guessing that means it would collect all the content elements from every object in the choices array? If so, that's quite cool.

polar light
#

Yup

#

You got it