解析JSON数据时出错。 JSONException:字符输入结束

时间:2014-02-06 06:11:27

标签: php android mysql json parsing

这是我用于解析的PHP代码片段。

$result=mysql_query($qry);

    $Json="{";
    for($i=1;$i<=$count;$i++)
    {
    $row = mysql_fetch_row($result)
    $newRow=setJson($i,$row);
    if($i!=$count)
    $Json=$Json.$newRow.",";
    else
    $Json=$Json.$newRow;
    }
    $Json=$Json."}";

    $response["success"]=1;
    $response["count"]=$count;
    $response["rows"]=$Json;

    echo json_encode($response);

创建新行的功能

function setJson($i,$row)
{
$setRow="\""$i."\":[".$row."]";
return $setRow;
}

我用php开发了这个。 我试图将MySQL结果解析为以下格式。对于DB中的每一行。我需要在我的应用程序中将其更新为SQLite DB。

    {
    "success":1,
    "error":0,
    "rows":{
            "1":["abc","123"],
            "2":["xxx","909"],
            "3":["bcn","1bc"]
        }
}


{
  "tag": "syncMe",
  "success": 1,
  "error": 0,
  "count": "8",
  "rows": "{
\"1\":[\"Porotta\",\"22\",\"652+2\",\"veg\",\"dinner\"],
\"2\":[\"chicken curry\",\"90\",\"sdaS\",\"veg\",\"dinner\"],
\"3\":[\"Assd\",\"12\",\"looo\",\"veg\",\"dinner\"]}"
}

如何删除JSON字符串中的斜杠。??

2 个答案:

答案 0 :(得分:1)

使用for循环将结果传递给一个数组变量。

然后使用json_encode(array_variable);

它将提供适当的json格式..

为什么需要手动格式化自己。

你可以尝试这种方式.. 注意:一些值我硬编码..

for($i=1;$i<=$count;$i++)
{
    $Json[$i]=array("abc","123");
}
$response["success"]=1;
    $response["count"]=3;
    $response["rows"]=$Json;

var_dump( json_encode($response));

答案 1 :(得分:0)

function setJson($i,$row)
{
$itemname=$row["item_name"];
$price=$row["price"];
$contents=$row["contents"];
$type=$row["type_of_item"];
$catagory=$row["catagory"];
//$setRow[]=array("\"".$i."\"" => $row);
$setRow="\"".$i."\":[".$itemname."\",\"".$price."\",\"".$contents."\",\"".$type."\",\"".$catagory."\"]";
return $setRow;
}

此函数将我的JSON解析为我的要求。

相关问题