【发布时间】:2015-10-27 19:02:08
【问题描述】:
我编写了这个函数来构建一个 JSON 样式的字符串:
function createJsonFromResponse($response_json)
{
// output json
$output_json = '[';
// number of steps
$num_steps = count($response_json['routes'][0]['legs'][0]['steps']);
//echo $num_steps;
// fill the json
for($i = 0; $i<$num_steps; $i++)
{
// start parenthesis
$output_json .= '{';
// start latitude
$output_json .= '"start_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lat'] . ',';
// start longitude
$output_json .= '"start_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lng'] . ',';
// end latitude
$output_json .= '"end_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lat'] . ',';
// end latitude
$output_json .= '"end_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lng'] . ',';
// step length
$output_json .= '"step_length":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['distance']['value'] . ',';
// html instruction
$output_json .= '"instruction":"' . $response_json['routes'][0]['legs'][0]['steps'][$i]['html_instructions'] . '"';
// closure parenthesis
$output_json .= '}';
// insert comma if required
if($i != $num_steps-1)
$output_json .= ',';
}
$output_json .= ']';
return $output_json;
}
然后,我把这个函数的输出字符串给了另一个。第二个函数执行这个简单的动作:
$steps_dec = json_decode($steps_txt,true);
$steps_txt 是我之前生成的字符串。
无论如何,我测试json_decode 的输出是NULL,而如果在生成字符串的函数中,我注释添加字符串字段的行,一切正常。
它似乎只喜欢数字字段。
你能发现我的错误吗?
谢谢。
【问题讨论】:
-
错误 #1:构建自己的 json。永远不要那样做。构建一个原生数据结构(例如数组),然后
json_encode()它。您可能通过将原始 html 转储到 json 文本中引入了 JS 语法错误。 -
没有理由自己编码 JSON。只需创建一个
new stdClass()或 assocarray()并给它你想要的属性。然后使用json_encode。您可能正在创建格式错误的 JSON。 -
我同意 Marc B 和 CollinD 的观点,但是如果你想知道哪里出了问题,你必须先检查输出,用 JSONLint 或其他什么东西检查它,然后根据该追踪找到哪里错误是。
-
看看 PHP 告诉你什么:
$steps_dec = json_decode($steps_txt,true); if (json_last_error() !== JSON_ERROR_NONE) { die(json_last_error_msg()); } -
谢谢。您的建议首先创建一个数组,然后为我的目的创建一个 JSON。