PHP/JSON-删除在每个字符之前出现的某个特定字符 [英] PHP/JSON - Remove every occurence of certain character before another character
问题描述
我的JSON是特有的编码,因此我需要删除右引号之前的所有引号. (例如{之前的每个)是否可以在PHP中执行此操作,如果可以,如何执行?
"{{我想删除括号前所有出现的引号.
此处的JSON: http://devticker.pw/json-data.php >
此处的代码:
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;
问题是您要手动生成JSON的一部分,然后使用json_encode
对该字符串进行编码,这会转义不应转义的引号.这是错误的.使用str_replace
删除转义符是一种工作,而不是生成JSON的正确方法.
如果仅使用json_encode
生成JSON,则效果很好.这样的事情应该起作用:
// 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);
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);
这篇关于PHP/JSON-删除在每个字符之前出现的某个特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!