How to Format JSON Output With Perplexity API
🔍 WiseChecker

How to Format JSON Output With Perplexity API

When you use the Perplexity API to get answers from large language models, the raw response is a JSON object. You need to extract and format this data for use in your application, dashboard, or log file. The API returns structured data that includes the answer text, citations, and usage statistics. This article explains how to request JSON output from the Perplexity API and how to format the response for readability and further processing.

Key Takeaways: Formatting Perplexity API JSON Responses

  • Set response_format to json_object: Instructs the model to output valid JSON in the message content.
  • Use json.loads() in Python: Parses the API response string into a Python dictionary for easy access.
  • Apply json.dumps() with indent=2: Pretty-prints the JSON for human-readable logs or debugging output.

ADVERTISEMENT

Understanding Perplexity API JSON Responses

The Perplexity API uses a chat completions endpoint. Each request includes a list of messages and optional parameters. The response is always a JSON object with fields like id, object, created, model, choices, and usage. The choices array contains one or more response objects, each with a message field that holds the assistant reply. The message object has a content field with the answer text. To get structured JSON output, you must set the response_format parameter to { "type": "json_object" }. This tells the model to return its answer as a valid JSON string inside the content field. Without this parameter, the model returns plain text.

Prerequisites for using JSON output formatting include:

  • A valid Perplexity API key with access to the desired model, such as sonar-pro or sonar-small-chat.
  • The requests library in Python or equivalent HTTP client in your language of choice.
  • Familiarity with basic JSON parsing in your programming environment.

Steps to Request and Format JSON Output

Follow these steps to send a request to the Perplexity API and format the returned JSON for readability. The examples use Python, but the concepts apply to any language.

  1. Install the requests library if not already installed
    Open your terminal or command prompt and run pip install requests. This library handles HTTP requests to the API.
  2. Set your API key and endpoint URL
    Store your API key in an environment variable or directly in a variable. The endpoint is https://api.perplexity.ai/chat/completions. Example: api_key = os.getenv('PERPLEXITY_API_KEY') and url = 'https://api.perplexity.ai/chat/completions'.
  3. Define the request payload with response_format
    Create a dictionary with the model name, messages array, and response_format. Set "response_format": {"type": "json_object"}. The messages array must include a user message that instructs the model to output JSON. Example: {"role": "user", "content": "List three programming languages and their primary use cases in JSON format"}.
  4. Send the POST request
    Use requests.post(url, headers=headers, json=payload) where headers include "Authorization": f"Bearer {api_key}" and "Content-Type": "application/json".
  5. Parse the response JSON
    The API returns a JSON object. Call response.json() to convert it to a Python dictionary. Extract the assistant message content: content = response.json()['choices'][0]['message']['content']. This content is a JSON string.
  6. Parse the content JSON and pretty-print
    Use json.loads(content) to convert the content string to a Python dictionary. Then use json.dumps(data, indent=2) to format it with indentation. Print or log the result.

Complete Python Example

import requests
import json

api_key = 'your_api_key_here'
url = 'https://api.perplexity.ai/chat/completions'

payload = {
    "model": "sonar-pro",
    "messages": [
        {"role": "user", "content": "List three programming languages and their primary use cases in JSON format"}
    ],
    "response_format": {"type": "json_object"}
}

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.post(url, headers=headers, json=payload)
response_data = response.json()
content = response_data['choices'][0]['message']['content']
parsed = json.loads(content)
formatted = json.dumps(parsed, indent=2)
print(formatted)

ADVERTISEMENT

Common Mistakes and Things to Avoid

Forgot to set response_format to json_object

If you omit the response_format parameter, the model returns plain text. The content field will contain a natural language answer, not a JSON string. Always include the parameter in your payload.

The model returns invalid JSON in content

Even with response_format set, the model may occasionally output malformed JSON, especially if the prompt is ambiguous. Make sure your user message explicitly asks for JSON output. Wrap the request in a try-except block when calling json.loads() to handle parsing errors gracefully.

Not extracting the content string correctly

The API response contains the assistant message in choices[0].message.content. Some developers mistakenly try to parse the entire API response as the formatted JSON. Remember that the outer API response is always a JSON object, but the inner content is the JSON you want to format.

Using the wrong model

Not all Perplexity models support the response_format parameter. Models like sonar-small-chat and sonar-pro support it. Check the latest API documentation for model compatibility. Using an unsupported model causes an error.

Perplexity API JSON Output Methods

Item Raw API Response Formatted JSON Output
Description Full JSON object returned by the API endpoint Pretty-printed version of the assistant message content
Structure Contains id, object, created, model, choices, usage Contains only the data returned by the model in the content field
Use case Debugging, logging full request metadata Displaying answers, feeding into downstream systems
Python method response.json() json.dumps(json.loads(content), indent=2)

You can now request and format JSON output from the Perplexity API using the response_format parameter and Python’s json library. The key steps are setting the parameter in the payload, extracting the content string, and pretty-printing with json.dumps(). For production applications, add error handling around json.loads() to catch malformed responses. You can also extend the example to write the formatted JSON to a file or pass it to a web framework like Flask or FastAPI.

ADVERTISEMENT