1. <?php
  2. /**
  3. * Encodes JSON objects with error handling for hypothesis validation.
  4. *
  5. * @param mixed $data The data to encode.
  6. * @param string $hypothesis The hypothesis being validated (optional).
  7. * @return string Encoded JSON string or error message.
  8. */
  9. function encodeJsonForHypothesisValidation($data, $hypothesis = '') {
  10. $encoded = json_encode($data, JSON_PRETTY_PRINT); // Encode with pretty printing
  11. if ($encoded === false) {
  12. return "Error encoding JSON: " . json_last_error_msg(); // Return error message if encoding fails
  13. }
  14. if (!is_string($encoded)) {
  15. return "Error: JSON encoding resulted in a non-string value.";
  16. }
  17. if ($hypothesis !== '') {
  18. return "JSON: " . $encoded . "\nHypothesis: " . $hypothesis; // Combine JSON and hypothesis
  19. }
  20. return $encoded; // Return encoded JSON string
  21. }
  22. //Example Usage:
  23. // $my_data = ['name' => 'John Doe', 'age' => 30];
  24. // $encoded_json = encodeJsonForHypothesisValidation($my_data, "Age should be greater than 25");
  25. // echo $encoded_json . "\n";
  26. // $invalid_data = object();
  27. // $encoded_json = encodeJsonForHypothesisValidation($invalid_data);
  28. // echo $encoded_json . "\n";
  29. ?>

Add your comment