Skip to content
Advertisement

Json_encode returns json cells as string

I’ve got a database structure like this. I’m willing to get row as a json object for Json.net.

My php code is this

$check_query = mysqli_query($conn, "select * from users where name = '$name' and password = '$pass'");
$rows = array();
    while($r = mysqli_fetch_assoc($get_query)) {
       $rows[] = $r;
    }
if(count($rows) > 0) {
echo json_encode($rows[0]);
}

I’m getting json as this.

{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum@gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":"["electronics", "vacations"]","history":null,"token":"12562f39b990da0433d7be71992ed634"}

As you can see, subscriptions value is string. I need it to be array as it seems.

{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum@gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":["electronics", "vacations"],"history":null,"token":"12562f39b990da0433d7be71992ed634"}

Is there any way to achieve this. ?

Thanks a lot !

Advertisement

Answer

The way you’re retrieving that data is giving you the JSON value as a string. Storing it as JSON in the database is a good idea if it’s actually JSON data, but the mysqli driver will not automatically de-serialize it for you. If you want that sort of behaviour you’ll need to use an ORM.

When you’re having trouble with double encoding, check with var_dump to see what you’re actually working with. That would reveal the subscriptions key contains a JSON string, not an array as expected.

What you’ll have to do is manually de-serialize it prior to JSON encoding:

if (isset($r['subscriptions'])) {
  $r['subscriptions'] = json_decode($r['subscriptions']);
}

$rows[] = $r;

You will need to do this for any and all JSON encoded fields your results might have.

This way you’re JSON encoding a proper PHP data structure and not one that’s part PHP and part JSON string.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement