Home > Back-end >  How to validate json string in PHP like JSON_VALID in mysql?
How to validate json string in PHP like JSON_VALID in mysql?

Time:07-31

I would like to validate json string before inserting it into mysql database so that JSON_VALID constraint is not violated. Using json_decode like

json_decode($string, true, 512, JSON_THROW_ON_ERROR);

is not enough because

json_decode('["\u001f?\b\u0000\u0000\u0000\u0000\u0000\u0002\u0003KL)NKLI\u0003\u0000z,?o\u0007\u0000\u0000\u0000"]', true, 512, JSON_THROW_ON_ERROR);

throws no error but

select JSON_VALID('["\u001f?\b\u0000\u0000\u0000\u0000\u0000\u0002\u0003KL)NKLI\u0003\u0000z,?o\u0007\u0000\u0000\u0000"]') as result; 

returns false. How can I achieve my goal?

CodePudding user response:

The JSON is valid, that's why the PHP version doesn't throw an error. But in SQL you need to escape all the backslashes to make them literal, so they'll be seen by the JSON parser. This is why MySQL mistakenly claimed it's not valid.

> select JSON_VALID('["\\u001f?\\b\\u0000\\u0000\\u0000\\u0000\\u0000\\u0002\\u0003KL)NKLI\\u0003\\u0000z,?o\\u0007\\u0000\\u0000\\u0000"]') as result; 
 -------- 
| result |
 -------- 
|      1 |
 -------- 

CodePudding user response:

The string you calling a json string is a unicode. But you want to validate your json string using PHP so here is the code.

function json_validator($data=NULL) {

  if (!empty($data)) {

                @json_decode($data);
                return (json_last_error() === JSON_ERROR_NONE);
        }
        return false;
}

$jsonString = '["\u001f?\b\u0000\u0000\u0000\u0000\u0000\u0002\u0003KL)NKLI\u0003\u0000z,?o\u0007\u0000\u0000\u0000"]';

echo (json_validator($jsonString) ? "JSON is Valid" : "JSON is Not Valid");

Source

Well this return true, but the string is an escaped unicode in a json style.

  • Related