⊗ppSpJnPE 20 of 83 menu

Parser Errors When Parsing JSON in PHP

Using the json_last_error function, you can find out exactly which error occurred during JSON parsing. Let's see how this is done. Suppose we have invalid JSON:

<?php $json = '["a", "b", "c",]'; ?>

Let's try to parse it:

<?php $data = json_decode($json); var_dump($data); // will output null ?>

Since an error occurred, json_last_error when called will return the number of this error:

<?php $error = json_last_error(); var_dump($error); // error number ?>

The returned number can be compared with special PHP constants. Based on this, you can write code that catches various types of errors:

<?php switch (json_last_error()) { case JSON_ERROR_NONE: echo 'No errors'; break; case JSON_ERROR_DEPTH: echo 'Maximum stack depth reached'; break; case JSON_ERROR_STATE_MISMATCH: echo 'Incorrect bits or mode mismatch'; break; case JSON_ERROR_CTRL_CHAR: echo 'Invalid control character'; break; case JSON_ERROR_SYNTAX: echo 'Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: echo 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: echo 'Unknown error'; break; } ?>

A string with some JSON is given. Parse it into a PHP data structure. Output the parsing result or the reason for the error if parsing the JSON failed.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline