0

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?

1
  • jsonlint.com says it's valid. Commented Jul 31, 2022 at 0:31

2 Answers 2

1

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 |
+--------+
Sign up to request clarification or add additional context in comments.

3 Comments

He want to validate it using PHP.
Ok, so the problem was escaping.
@MuradAli The PHP is fine. I'm just showing why he got a different result in MySQL.
0

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";
}

2 Comments

Doesn't the JSON_THROW_ON_ERROR flag serve the same purpose?
Yeah, we can use that I just add the second method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.