# !pip install anthropic --upgrade
How to Use JSON Mode
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
When working with AI models like Claude, you may want to receive structured data in the form of JSON, rather than plain text. This allows for easier processing and extraction of information.
Although Claude doesn’t have a built-in “JSON mode,” you can still get reliable JSON output by following a few techniques:
- Use string parsing to extract the JSON from Claude’s response by finding the text between “{” and “}” characters.
- Provide a partial response in the “assistant” role to remove any preamble text before the JSON. For example, send “Here is the JSON requested:\n{” to start the JSON output immediately.
- If the JSON output is followed by additional text, you can use a stop sequence to truncate the response after the JSON ends.
For more complex prompts that may include multiple JSON outputs, you can instruct Claude to wrap each JSON object in specific XML-like tags. This makes it easier to extract the JSON using regular expressions later.
Once you have extracted the JSON string from Claude’s response, you can use the
json.loads()
function in Python to parse it into a dictionary or list, depending on the structure of the JSON.By following these techniques, you can effectively use Claude to generate structured JSON data, which can be easily integrated into your applications or workflows.
Remember, while Claude is capable of generating JSON, it’s essential to provide clear instructions and examples to ensure you get the desired output format.
import os
from dotenv import load_dotenv
load_dotenv()
True
= os.getenv("ANTHROPIC_API_KEY") api_key
import anthropic
= anthropic.Anthropic(
client # defaults to os.environ.get("ANTHROPIC_API_KEY")
=api_key,
api_key )
= """
recipe_text Banana Bread Recipe
Ingredients:
3 ripe bananas, mashed
1/3 cup melted butter
1/2 cup sugar
1 egg, beaten
1 teaspoon vanilla
1 teaspoon baking soda
Pinch of salt
1 1⁄2 cups all-purpose flour Instructions: Preheat oven to 350°F. Mix butter into the mashed bananas in a large mixing bowl. Mix in the sugar, egg, and vanilla. Sprinkle the baking soda and salt over the mixture and mix in. Add the flour last, mix just enough to blend the ingredients. Pour mixture into a buttered 4x8 inch loaf pan. Bake for 1 hour. Cool on a rack before removing from pan. Slice to serve. """
= f"""
prompt
RECIPE: {recipe_text}
Give me a JSON dictionay of ingredients and quantities.
"""
= client.messages.create(
message ="claude-3-opus-20240229",
model=1024,
max_tokens=[
messages
{"role": "user",
"content": prompt
},
{"role":"assistant",
"content": "Here is the JSON requested:\n{"
}
]0].text
).content[print(message)
"ingredients":[
{
"item":"ripe bananas",
"amount":"3",
"notes":"mashed"
},
{
"item":"butter",
"amount":"1/3 cup",
"notes":"melted"
},
{
"item":"sugar",
"amount":"1/2 cup"
},
{
"item":"egg",
"amount":"1",
"notes":"beaten"
},
{
"item":"vanilla",
"amount":"1 teaspoon"
},
{
"item":"baking soda",
"amount":"1 teaspoon"
},
{
"item":"salt",
"amount":"1 pinch"
},
{
"item":"all-purpose flour",
"amount":"1 1/2 cups"
}
]
}
import json
= json.loads("{" + message[:message.rfind("}") + 1])
output_json output_json
{'ingredients': [{'item': 'ripe bananas', 'amount': '3', 'notes': 'mashed'},
{'item': 'butter', 'amount': '1/3 cup', 'notes': 'melted'},
{'item': 'sugar', 'amount': '1/2 cup'},
{'item': 'egg', 'amount': '1', 'notes': 'beaten'},
{'item': 'vanilla', 'amount': '1 teaspoon'},
{'item': 'baking soda', 'amount': '1 teaspoon'},
{'item': 'salt', 'amount': '1 pinch'},
{'item': 'all-purpose flour', 'amount': '1 1/2 cups'}]}
Generate Month names in English, Tamil, Spanish, and French
= client.messages.create(
message ="claude-3-opus-20240229",
model=1024,
max_tokens=[
messages
{"role": "user",
"content": "Generate month names in English, Tamil, Spanish, and French in JSON format. Language as keys, and list of month names as values."
},
{"role":"assistant",
"content": "Here is the JSON requested:\n{"
}
]0].text
).content[print(message)
"English":
[
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"Tamil":
[
"ஜனவரி",
"பிப்ரவரி",
"மார்ச்",
"ஏப்ரல்",
"மே",
"ஜூன்",
"ஜூலை",
"ஆகஸ்ட்",
"செப்டம்பர்",
"அக்டோபர்",
"நவம்பர்",
"டிசம்பர்"
],
"Spanish":
[
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"French":
[
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
}
= json.loads("{" + message[:message.rfind("}") + 1])
output_json output_json
{'English': ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'],
'Tamil': ['ஜனவரி',
'பிப்ரவரி',
'மார்ச்',
'ஏப்ரல்',
'மே',
'ஜூன்',
'ஜூலை',
'ஆகஸ்ட்',
'செப்டம்பர்',
'அக்டோபர்',
'நவம்பர்',
'டிசம்பர்'],
'Spanish': ['enero',
'febrero',
'marzo',
'abril',
'mayo',
'junio',
'julio',
'agosto',
'septiembre',
'octubre',
'noviembre',
'diciembre'],
'French': ['janvier',
'février',
'mars',
'avril',
'mai',
'juin',
'juillet',
'août',
'septembre',
'octobre',
'novembre',
'décembre']}
"English"] output_json[
['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']