javascript - 解码json代码时出错

标签 javascript php json wordpress

我需要解码 json 的帮助

if($loop->have_posts()) :
    $json = '{';
    $json .= '
    "api_status":1,
    "api_message":"success",
    "data": [';
    while ( $loop->have_posts() ) : $loop->the_post();
        $json .= '{
        "id":'.get_the_ID().',
        "post_name":"'.get_the_title().'"
        },
        ';
    endwhile;

    $json = substr($json,0,-1);
    $json .= ']}';

    echo $json;
endif;
break;
}

我的错误是

enter image description here

在最后一个}中我仍然有,,所以我需要删除它。

但我不知道怎么办? 有人帮助我吗?

最佳答案

正如评论中提到的,json_encode 是正确的选择。

$toEncode = array(
    "api_status" => 1,
    "api_message" => "success",
    "data" => array()
);

while ($loop->have_posts()) {
    $loop->the_post();
    array_push($toEncode["data"], array(
        "id" => get_the_ID(),
        "post_name" => get_the_title()
    ));
}

echo json_encode($toEncode);

但是,我不太明白你们的帖子系统是如何工作的。您是否使用某种类型的迭代器?

关于javascript - 解码json代码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173260/

相关文章:

php - 使用 jquery 的一页 Codeigniter 站点? Ajax ?

c# - 如何获取具有特定名称的所有节点

c# - 使用 yield return 可以返回 JSON "live"吗?

javascript - 在浏览器中使用 ES6 模块时,我应该在 `script` 标签中引用文件吗

javascript - 带计时器的 Jquery/Ajax 调用

php - 如何以json格式在浏览器上查看印地语字体

javascript - 获取 XMLHttpRequest 无法在第二次 api 调用 Instagram 上加载

javascript - 如何更改 javascript 对象的颜色?

javascript - 我怎样才能在情节上获得静态工具提示,highstock?

带有端口号问题的 PHP Curl