Every AI developer has seen this nightmare:
# AI API returns malformed JSON
response = '{"name": "John", "age": 30' # Missing closing brace
json.loads(response) # ❌ JSONDecodeError!
AI models sometimes return malformed JSON — missing braces, trailing commas, markdown code blocks wrapping the JSON. It's one of the most common pain points in AI development.
jshape just dropped on PyPI and it fixes this. Here's how to use it with NexaAPI for bulletproof AI applications.
Install
pip install jshape nexaapi
Basic Usage
import jshape
from nexaapi import NexaAPI
client = NexaAPI(api_key='YOUR_API_KEY') # Get free key at nexa-api.com
# Get AI response (might be malformed JSON)
response = client.chat.completions.create(
model='gpt-4o',
messages=[{"role": "user", "content": "Return a JSON user profile"}]
)
raw_json = response.choices[0].message.content
# Fix malformed JSON with jshape
data = jshape.loads(raw_json) # Works even if malformed!
print(data) # ✅ Always valid Python dict
Real-World Example: Image Generation with AI Config
import jshape
from nexaapi import NexaAPI
client = NexaAPI(api_key='YOUR_API_KEY')
def generate_image_from_ai_config(user_request: str) -> str:
# Step 1: Get image config from AI
config_response = client.chat.completions.create(
model='gpt-4o',
messages=[{
"role": "user",
"content": f"Generate JSON config for this image: {user_request}"
}]
)
# Step 2: Fix malformed JSON (jshape handles edge cases)
config = jshape.loads(config_response.choices[0].message.content)
# Step 3: Generate image with NexaAPI ($0.003/image)
image = client.image.generate(
model='stable-diffusion-xl',
prompt=config['prompt'],
width=config.get('width', 1024),
height=config.get('height', 1024)
)
return image.image_url
JavaScript Version
import NexaAPI from 'nexaapi'; // npm install nexaapi
import { repair, parse } from 'jshape'; // npm install jshape
const client = new NexaAPI({ apiKey: 'YOUR_API_KEY' });
async function generateWithAIConfig(userRequest) {
const configResponse = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: `JSON config for: ${userRequest}` }]
});
// Fix malformed JSON
const config = parse(repair(configResponse.choices[0].message.content));
const image = await client.image.generate({
model: 'stable-diffusion-xl',
prompt: config.prompt
});
return image.imageUrl;
}
Top comments (0)