Skip to content

Instantly share code, notes, and snippets.

@mattimatti
Last active August 24, 2023 16:41
Show Gist options
  • Select an option

  • Save mattimatti/81f0715b8a66067d48974b9213146239 to your computer and use it in GitHub Desktop.

Select an option

Save mattimatti/81f0715b8a66067d48974b9213146239 to your computer and use it in GitHub Desktop.
Fix truncated incomplete json
<?php
function fixIncompleteJson($partialJson) {
$jsonWithoutBraces = trim($partialJson, '{}');
$pairs = explode(',', $jsonWithoutBraces);
$validPairs = [];
foreach ($pairs as $pair) {
if (preg_match('/^\s*"([^"]+)"\s*:\s*"([^"]+)"\s*$/', $pair, $matches)) {
$key = $matches[1];
$value = $matches[2];
$validPairs[] = "\"$key\":\"$value\"";
}
}
$fixedJson = '{' . implode(',', $validPairs) . '}';
return $fixedJson;
}
$input = '{"testMode":"0","event_type":"guaranteed","event_date":"2023-04-03T19:41:42Z","event_resource":"payments","payment_id":"QOE584090823","amount_from":"509700","currency_from":"USD","amount_to":"455800","currency_to":"EUR","status":"guaranteed","expiration_d\'';
$decodedJson = null;
while ($decodedJson === null) {
$fixedJson = fixIncompleteJson($input);
$decodedJson = json_decode($fixedJson);
if ($decodedJson === null) {
$input = $fixedJson;
}
}
echo $fixedJson;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment