PHP code example of edgaras / llm-json-cleaner

1. Go to this page and download the library: Download edgaras/llm-json-cleaner library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

edgaras / llm-json-cleaner example snippets




use Edgaras\LLMJsonCleaner\JsonCleaner;

$llmResponse = "Hi there! Please find the details below:\n\n{
    \"task\": \"generate_report\",
    \"parameters\": {
        \"date\": \"2025-02-17\",
        \"format\": \"pdf\"
    }
}\n\nLet me know if you need further assistance.";

// Return JSON only
$extractJson = JsonCleaner::extract($llmResponse, false);
echo $extractJson;
// {"task":"generate_report","parameters":{"date":"2025-02-17","format":"pdf"}}

// Return JSON only as an array
$extractJsonAsArray = JsonCleaner::extract($llmResponse, true);
print_r($extractJsonAsArray);
// (
//  [task] => generate_report
//  [parameters] => Array
//      (
//          [date] => 2025-02-17
//          [format] => pdf
//      )
// )

// Trailing commas
$json = JsonCleaner::extract('{"name": "Alice", "age": 30,}', true);
// ['name' => 'Alice', 'age' => 30]

// Single-quoted JSON
$json = JsonCleaner::extract("{'name': 'Alice'}", true);
// ['name' => 'Alice']

// Unquoted keys
$json = JsonCleaner::extract('{name: "Alice", active: true}', true);
// ['name' => 'Alice', 'active' => true]

// Multiline string values (literal newlines inside strings)
$json = JsonCleaner::extract('{"text": "line one
line two"}', true);
// ['text' => "line one\nline two"]

// Top-level arrays
$json = JsonCleaner::extract('Here: [{"id":1},{"id":2}] done.', true);
// [['id' => 1], ['id' => 2]]



use Edgaras\LLMJsonCleaner\JsonValidator;


$json = '{
  "order_id": 401,
  "customer": "Alice",
  "payment_methods": [
    {
      "method_id": "p1",
      "type": "Credit Card"
    },
    {
      "method_id": "p2",
      "type": "PayPal"
    }
  ]
}';

$schema = [
  'order_id' => [';
var_dump($validator);
// bool(true)


$schemaNotFull = [
  'order_id' => ['