dongyi5425 2013-12-05 13:51
浏览 24
已采纳

从数据库中的数组创建有效的JSON

I'm trying to put my data into Json format. The code seems to work fine, I get a Json format, but the data is not Json valid. This is how the json comes out:

({
"sample": [
    {
        "0": "12",
        "image_id": "12",
        "1": "background.JPG",
        "path": "background.JPG",
        "2": "background.JPG",
        "name": "background.JPG",
        "3": "image\/jpeg",
        "type": "image\/jpeg",
        "4": "51600",
        "size": "51600",
        "5": "4",
        "likes": "4",
        "6": "zwitserland",
        "onderwerp": "zwitserland",
        "7": "Landscape from cableway",
        "beschrijving": "Landscape from cableway"
    },
    {
        "0": "13",
        "image_id": "13",
        "1": "IMG_1052.JPG",
        "path": "IMG_1052.JPG",
        "2": "IMG_1052.JPG",
        "name": "IMG_1052.JPG",
        "3": "image\/jpeg",
        "type": "image\/jpeg",
        "4": "45434",
        "size": "45434",
        "5": "28",
        "likes": "28",
        "6": "belgium",
        "onderwerp": "belgium",
        "7": "Highway in Belgium",
        "beschrijving": "Highway in Belgium"
    }, ETC ETC

This is my php code. When I put my code into a Json editor I get the following error:

Parse error on line 1: ({ "sample": [ ^ Expecting '{', '['

$arr = array();
$rs = mysql_query("SELECT * FROM images");

while($obj = mysql_fetch_array($rs)) {
$arr[] = $obj;

}
$json = '{"sample":'.json_encode($arr).'}';
echo $_GET['jsoncallback'] . '(' . $json . ')';
  • 写回答

1条回答 默认 最新

  • doulangbi6869 2013-12-05 13:53
    关注

    You shouldn't try manually building your own JSON, for reasons exactly like this.

    Use this and this alone.

    $json = json_encode(array("sample" => $arr));
    

    Or

    $json = json_encode(array("sample" => array($_GET["jsoncallback"] => $arr)));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?