My JSON is encoding peculiarly, so I need to remove every quote before a right-opening bracket. (e.g. every " before a {) Is it possible to do this in PHP, and if so, how?
"{ I would want to remove every occurrence of the quote before the bracket.
JSON here: http://devticker.pw/json-data.php
Code here:
while($row = mysqli_fetch_array($result))
{
$data[] = '{"c": [{ "v": ' . $row['Timestamp'] . '"},{"v":' . $row['USD'] . '} ]}';
}
$str = json_encode(array("rows"=>$data));
$str = substr($str, 1);
$str = str_replace("\"{", "{", $str);
$str = '{"cols":[{"type":"string"},{"type":"number"}],' . $str;
$str = stripslashes($str);
echo $str;
The problem is you are generating part of the JSON manually and then encoding that string with json_encode
, which is escaping the quotes that should not be escaped. This is wrong. Using str_replace
to remove the escaping is a workarround, not the correct way to generate your JSON.
If you generate your JSON using only json_encode
it works well. Something like this should work:
// your columns
$cols = array();
$cols[0] = array('type' => 'string');
$cols[1] = array('type' => 'number');
// your rows
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$r = new stdClass();
$r->c = array();
$r->c[0] = array('v' => $row['Timestamp']);
$r->c[1] = array('v' => $row['USD']);
$rows[] = $r;
}
// the final result
$result = array(
'cols' => $cols,
'rows' => $rows
);
// don't forget this
header('Content-Type: application/json');
echo json_encode($result);
$json = str_replace('"{','{',$json)
Really can't understand why you need to do this (and why you are manupulating raw JSON string), but you can simply use the string-replacement function of php, str_replace:
$your_json_string = str_replace("\"{", "{", $your_json_string);
What version of PHP are you using?
If 5.3 or greater than you can use this:
return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
Frameworks like drupal have handled this stuff - you could probably rip some code from here to roll your own json_encode function https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_json_encode/7
Try
while($row = mysqli_fetch_array($result))
{
$data[] = array("c" => array(array( "v" => $row['Timestamp']), array("v" => $row['USD'] ))));
}
$rows = array("rows"=>$data));
$cols = array("cols" => array(array("type"=>"string"),array("type"=>"number")),$row);
$str = json_encode($cols);
echo $str;