Created
October 24, 2024 14:51
-
-
Save muhdkhokhar/fc253fa5ec86a4b3b557896e7c877d17 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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