0

I need to check if an option value from database is a json object.

This funtion following cannot work :

function isJson( string $str, $is_assoc = true ){
    json_decode( $str, $is_assoc );
    return (json_last_error() == JSON_ERROR_NONE);
}

It´s normal because with an SQL query I got :

a:2:{i:3;a:4:{s:5:"title";s:0:"";s:4:"text";s:503:"...}}

instead of

{ '3' : { 'title' : "", 'text' : "..." }...}}

How can I do to check if this data is a json object and to get this data as object ?

Final goal : Reaplace correclty value for json object in the database without breaking serialized data.

1
  • Do you have control of the data? is it prepared by yourself before saving it to database? Did you try unserialize it for further manipulations? Commented Apr 7, 2020 at 17:32

2 Answers 2

2

To check if a string from database is like a:2:{i:3;a:4:{s:5:"title";s:0:"";s:4:"text";s:503:"...}}, you can use the function is_serialized()

To get the data as php array :

if(is_serialized($data_as_string)){
    $data_as_array = unserialize( $data_as_string);
}
1
  • This is the answer. In the OP's provided example, they are dealing with serialized data. While serialized data appears to have similarities to JSON encoded data they are not interchangeable and have notable differences. Commented May 2 at 16:24
0

You can test if it is JSON with this PHP code:

echo json_decode($s) === null ? "not json" : "json";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.