Skip to content

Instantly share code, notes, and snippets.

@muhdkhokhar
Created October 24, 2024 14:51
Show Gist options
  • Save muhdkhokhar/fc253fa5ec86a4b3b557896e7c877d17 to your computer and use it in GitHub Desktop.
Save muhdkhokhar/fc253fa5ec86a4b3b557896e7c877d17 to your computer and use it in GitHub Desktop.
function stringifyWithLimit(obj, maxSizeMB = 5) {
const maxSizeBytes = maxSizeMB * 1024 * 1024; // Convert MB to bytes
let jsonString = JSON.stringify(obj);
// Check if the JSON string exceeds the maximum size
if (jsonString.length > maxSizeBytes) {
console.warn(`The JSON string exceeds the ${maxSizeMB} MB limit. Truncating output.`);
// Truncate the JSON string to the max size limit
jsonString = jsonString.substring(0, maxSizeBytes);
// Since truncating a JSON string may result in invalid JSON,
// we can close off the truncated JSON safely here (e.g., with an ellipsis).
jsonString += '...';
}
return jsonString;
}
// Example usage:
const largeObject = { /* your large object here */ };
const limitedString = stringifyWithLimit(largeObject);
console.log(limitedString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment