我正在尝试从php中删除json_encoded数据中的制表符?每当我尝试以JSON enocded格式从脚本中获取数据时,我使用下面的代码来解析我的数据,但无法解析 jsonStr 。
我得到的错误是
错误:JSON.parse:JSON第1行第1列的意外字符 数据
代码
jsonStr = data.toString();
jsonStr = JSON.stringify(jsonStr.replace("\t",""));
totJSON = JSON.parse(jsonStr['totalActionItems']);
如何解决此错误以正确解析格式正确的json字符串?
修改
更正后的解析代码(JS)
$.ajax({url: "/dashboard/chartdata.php?chart=buildup", success: function(data)
{
jsonStr = data.replace(/\t/g, "");
console.log(jsonStr);
json = JSON.parse(jsonStr);
totJSON = json['totalActionItems'];
PHP代码
function getData($field, $rows)
{
$minDate = $rows[0][$field];
$maxDate = $rows[count($rows)-1][$field];
$date = $minDate;
$findDate = $minDate;
$idx = 0;
$tot = 0;
$dates = array();
$numActionItems = array();
while ($date < $maxDate)
{
if ($rows[$idx][$field] == $date)
{
$tot += $rows[$idx]['numactionitems'];
$idx++;
}
$timestamp = strtotime($date);
$date = date('Y-m-d', strtotime($date . "+1 days"));
$numActionItems[] = array('x'=>$timestamp*1000, 'y'=>$tot);
}
return $numActionItems;
}
function getBuildUpData($field)
{
$manageCharts = new manageCharts();
$rows = $manageCharts->buildup($field);
$items = getData($field, $rows);
return $items;
}
if (isset($_GET['chart']) && $_GET['chart'] == 'buildup')
{
$json = json_encode(['totalActionItems' => getBuildUpData('assigneddate'),
'ecdItems' => getBuildUpData('ecd'),
'originalDueItems' => getbuildUpData('duedate'),
'closedItems' => getBuildUpData('closeddate')]);
echo $json;
}
答案 0 :(得分:0)
以下代码帮助生成了正确的json进行处理。
jsonStr = data.replace(/\t/g, "");
//console.log(jsonStr);
json = JSON.parse(jsonStr);
totJSON = json['totalActionItems'];