简体   繁体   中英

Remove extra double quotes in generated JSON string from fetched DB results

I have searched Google that might answer my question but then I came into a dead brain.

I have some JSON output from my query

$myQuery = "SELECT title, start FROM reserved_b";
$result = $mysqli->query($myQuery) or die($mysqli->error);
$data = array();
while ( $row = $result->fetch_assoc() ){
   $data[] = json_encode($row);
}

$json = json_encode($data);
echo $str = str_replace('\\', '', $json);

then this is the result

["{"title":"Wedding","start":"2015-01-29 00:00:00"}","{"title":"Gathering","start":"2015-01-23 01:00:00"}"]

I just want to remove the double quotes, and the output should be like this:

[{"title":"Wedding","start":"2015-01-29 00:00:00"},{"title":"Gathering","start":"2015-01-23 01:00:00"}]

Is it possible?

Thank you in advance for your answers.

No, don't use string operations (str_replace) to solve this problem. The reason why your JSON string is not well constructed is because you have a superfluous/unneeded encoding while inside the loop.

Just finish creating the array structure, then finally encode:

$myQuery = "SELECT title, start FROM reserved_b";
$result = $mysqli->query($myQuery) or die($mysqli->error);
$data = array();
while ( $row = $result->fetch_assoc() ){
    $data[] = $row; // just push it as an array
}
// then finally, encode in the end
$json = json_encode($data);
echo $json;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM