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.
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
Define expected JSON schema.
Validate AI-generated output against the schema.
Extract and format data into JSON.
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
Writes source code or scripts from a description.
Pulls structured data fields from unstructured text.
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
colorandcountries, 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
- type: is-json
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.