Debugging JSON API responses is a crucial skill for modern developers. Whether you're dealing with malformed JSON, unexpected data structures, or integration issues, this guide will help you troubleshoot effectively.
{
"status": "success",
"data": {
"users": [
{
"name": "John",
"age": 30,
} // ❌ Trailing comma
]
}
}
{
"user_id": "123", // ❌ Should be number
"age": "30" // ❌ Should be number
}
{
"user": {
"name": "John"
// ❌ Missing email, id, etc.
}
}
try {
const data = JSON.parse(response);
console.log('Valid JSON:', data);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
user_id: { type: "number" },
name: { type: "string" },
email: { type: "string", format: "email" }
},
required: ["user_id", "name", "email"]
};
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
console.log('Validation errors:', validate.errors);
}
# Validate JSON with jq
curl -s api.example.com/users | jq .
# Pretty print JSON
echo '{"name":"John","age":30}' | jq .
# Extract specific fields
curl -s api.example.com/users | jq '.users[0].name'
function processApiResponse(response) {
// Validate JSON structure
if (!response || typeof response !== 'object') {
throw new Error('Invalid response format');
}
// Check required fields
if (!response.data || !Array.isArray(response.data)) {
throw new Error('Missing or invalid data array');
}
return response.data;
}
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return processApiResponse(data);
} catch (error) {
console.error('API Error:', error.message);
// Return default or cached data
return getDefaultUserData();
}
}
console.group('API Debug Info');
console.log('Endpoint:', endpoint);
console.log('Request:', requestData);
console.log('Response Status:', response.status);
console.log('Response Data:', responseData);
console.groupEnd();
Effective JSON API debugging requires the right tools, techniques, and mindset. By following these practices and using tools like JSON Sage, you can quickly identify and resolve API issues.
Start debugging your JSON APIs more effectively with JSON Sage's comprehensive toolkit!