adbeno
adbeno

Reputation: 33

How to validate json string in PHP like JSON_VALID in mysql?

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?

Upvotes: 0

Views: 1015

Answers (2)

Barmar
Barmar

Reputation: 782181

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 |
+--------+

Upvotes: 1

Murad Ali
Murad Ali

Reputation: 418

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. 😂

Updated Method 2

$jsonString = '["\u001f?\b\u0000\u0000\u0000\u0000\u0000\u0002\u0003KL)NKLI\u0003\u0000z,?o\u0007\u0000\u0000\u0000"]';
try {
    json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR);
} catch (\Exception $e) {
    // echo $e->getMessage();
    echo "Invalid JSON";
}

Upvotes: 0

Related Questions