Prompt Chain

Generate Structured JSON Output

Generate structured JSON output from LLM responses with precise field names and no nesting. Ideal for data extraction and API integration.


78
Spark score
out of 100
Updated 3 months ago
Version 1.0.0

Add to Favorites

Why it matters

Ensure your AI models consistently produce valid JSON output for seamless integration into your applications and data pipelines.

Outcomes

What it gets done

01

Define expected JSON schema.

02

Validate AI-generated output against the schema.

03

Extract and format data into JSON.

04

Handle errors for invalid JSON.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/pfoo-json-output | bash

Capabilities

What this chain does

Generate code

Writes source code or scripts from a description.

Extract

Pulls structured data fields from unstructured text.

Query a database

Writes and executes SQL or NoSQL queries on databases.

Overview

Json Output

What it does

This prompt chain extracts information from language model responses and formats it into a flat JSON object. It strictly uses predefined field names and avoids nested structures, ensuring consistent and machine-readable output for data processing.

How it connects

Use this chain when you need to reliably extract specific data points from an LLM's response into a predictable JSON format, such as for populating databases or integrating with other applications.

Source README

yaml-language-server: $schema=https://promptfoo.dev/config-schema.json

description: 'JSON object evals'

prompts:

  • 'Output a JSON object that contains the keys color and countries, describing the following object: {{item}}'

providers:

  • id: openai:chat:gpt-4.1-mini
    config:
    response_format:
    type: json_object

tests:

  • vars:
    item: Banana
    assert:

    • type: is-json
    • type: javascript

      Parse the JSON and test the contents

      value: JSON.parse(output).color === 'yellow' && JSON.parse(output).countries.includes('Ecuador')
  • vars:
    item: Passion fruit
    options:

    Parse the JSON before all assertions

    transform: JSON.parse(output)
    assert:

    • type: is-json

      Optional JSON schema

      value:
      required:
      - 'color'
      - 'countries'
      type: object
      properties:
      color:
      type: string
      countries:
      type: array
      items:
      type: string
    • type: javascript

      JSON.parse is no longer necessary here

      value: output.color === 'purple' && output.countries.includes('Brazil')
    • type: contains-any
      transform: output.countries
      value:
      • Guatemala
      • Costa Rica
      • India
      • Indonesia

Uncomment to parse JSON outputs for ALL tests

defaultTest:

options:

transform: JSON.parse(output)

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.