Reputation: 131
I need to get a JSON Object from Database, convert it to php object and foreach the key=>value pairs.
The JSON Object is stored with JSON.stringify(obj) in MySQL text field. Afterwards i get the data with PDO, but i have same unterstanding problem how to decode the json object to an object in php. The Result is everytime a string.
$export = $data['document']->tax_rates;
$export = json_encode($export);
$export = json_decode($export);
var_dump($export);
echo($export)
// only test
var_dump(json_decode($data['document']->tax_rates));
var_dump($data['document']->tax_rates)
$jsontest = json_decode('{"a":1,"b":2}');
var_dump($jsontest);
The result is:
string(42) "{"7":39729.69,"19":107.73}" // var_dump
{"7":39729.69,"19":107.73} // echo
NULL // result of decode without encode before
string(42) "{"7":39729.69,"19":107.73}" // var_dump raw data['document']
//test result as it should be
object(stdClass)#21 (2) {
["a"]=>
int(1)
["b"]=>
int(2)
}
Debugging the Json output the error: JSON_ERROR_SYNTAX. But is is a valid JSON Object.
How can i genereate an php object here and where is my issue in this case? If i understand correct, the output is a string because since it is stored in the text field, it is already a string. If it is so, is it possible to handle it this way or is it impossible? Thanks.
Upvotes: 0
Views: 42
Reputation: 146450
What you have is not JSON but HTML-encoded JSON. You can recover the original data with html_entity_decode():
$html = '[{"7":3.5,"19":19,"20":20}]';
$json = html_entity_decode($html);
echo $json;
But it'd be better to identify and fix the bug that's causing invalid data form being stored in the first place.
Upvotes: 2