How to Parse Chat Completion JSON in Python

Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 14 views 0 copies

Python code

31 lines
Python 3.9+
import json

def parse_chat_response(raw: str) -> dict:
    data = json.loads(raw)
    choice = data["choices"][0]
    return {
        "content": choice["message"]["content"],
        "finish_reason": choice["finish_reason"],
        "model": data["model"],
    }

if __name__ == "__main__":
    mock_response = '''
    {
      "id": "chatcmpl-123",
      "object": "chat.completion",
      "model": "gpt-3.5-turbo",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Hello! How can I help you today?"
          },
          "finish_reason": "stop"
        }
      ]
    }
    '''
    result = parse_chat_response(mock_response)
    print(json.dumps(result, indent=2))

Output

stdout
{
  "content": "Hello! How can I help you today?",
  "finish_reason": "stop",
  "model": "gpt-3.5-turbo"
}

How it works

The json.loads call converts the raw JSON string into a Python dictionary, letting you access nested fields with bracket notation. The choices list is indexed first, because each response can contain multiple choices and you want the first one. The message object nested inside holds the assistant's reply content. Extracting finish_reason and model gives you metadata for logging or branching logic. This pattern mirrors what you'd do with real API responses, just with dummy data for testing.

Common mistakes

  • Assuming `choices` list always has an element — always guard against empty responses.
  • Forgetting that the content field may be null for tool calls or function invocations.
  • Using `json.load` instead of `json.loads` when reading from a string instead of a file.

Variations

  1. Use `choice["message"].get("content")` to safely handle missing content.
  2. Use `json.loads(raw)["choices"][0]["message"]["content"]` for a one-liner when you don't need the other fields.

Real-world use cases

  • Extracting assistant replies from an OpenAI API response in a chatbot backend.
  • Logging finish reasons to detect truncated or stopped completions in production.
  • Testing prompt logic with mock responses before wiring up real API calls.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.