1. /**
  2. * Converts JSON objects for diagnostics with synchronous execution.
  3. *
  4. * @param {object} jsonObject The JSON object to convert.
  5. * @param {string} format The desired output format ('string', 'array', 'key_value_pairs').
  6. * @returns {string|Array|string} The converted JSON object in the specified format.
  7. * @throws {Error} If the format is invalid.
  8. */
  9. function convertJsonForDiagnostics(jsonObject, format) {
  10. if (!jsonObject || typeof jsonObject !== 'object') {
  11. return "Invalid JSON object"; // Handle invalid input
  12. }
  13. switch (format) {
  14. case 'string':
  15. try {
  16. return JSON.stringify(jsonObject, null, 2); // Pretty print JSON string
  17. } catch (error) {
  18. return "Error stringifying JSON: " + error.message;
  19. }
  20. case 'array':
  21. try {
  22. return JSON.stringify(jsonObject, null, 2); // Convert to JSON array string
  23. } catch (error) {
  24. return "Error stringifying JSON array: " + error.message;
  25. }
  26. case 'key_value_pairs':
  27. let keyValuePairs = "";
  28. for (const key in jsonObject) {
  29. if (jsonObject.hasOwnProperty(key)) {
  30. keyValuePairs += `${key}: ${jsonObject[key]}\n`;
  31. }
  32. }
  33. return keyValuePairs;
  34. default:
  35. throw new Error("Invalid format specified. Choose from 'string', 'array', or 'key_value_pairs'.");
  36. }
  37. }

Add your comment