Last active
August 24, 2023 16:41
-
-
Save mattimatti/81f0715b8a66067d48974b9213146239 to your computer and use it in GitHub Desktop.
Fix truncated incomplete json
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
| <?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