How to check and get json object in WP database?

admin2025-01-07  4

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.

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.

Share Improve this question edited Apr 7, 2020 at 20:23 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Apr 7, 2020 at 17:00 J.BizMaiJ.BizMai 9002 gold badges10 silver badges30 bronze badges 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? – 西門 正 Code Guy - JingCodeGuy Commented Apr 7, 2020 at 17:32
Add a comment  | 

1 Answer 1

Reset to default 0

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);
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736254047a173.html

最新回复(0)