我正在尝试将JSON数组添加到JSON对象。我的代码就像这样
{
"status": "True",
"users": {
"id": "16",
"name": "user",
"email": "user@example.com",
"friends": [
{
"id": "11",
"name": "frnd1",
"email": "frnd@example.com"
},
{
"id": "12",
"name": "frnd2",
"email": "frnd@example.com"
}
]
}
}
我在执行以下代码时遇到JSONException,
// check for user
$user = $db->getUserByEmailAndPassword($username, $password);
if ($user != false) {
// user found
$response["status"] = "True";
$userID = $user["id"];
$response["users"]["id"] = $user["id"];
$response["users"]["name"] = $user["name"];
$response["users"]["email"] = $user["email"];
$result = mysqli_query($con1,"SELECT *
FROM friends
where userID = '$userID'");
$response["users"]["friend"]=array();
while($row = mysqli_fetch_array($result))
{
array_push($response["users"]["friend"], $row);
}
}
echo json_encode($response);
我在这个文件中建立了$ con1连接。 谁能指出我在这里做错了什么?
答案 0 :(得分:0)
试试这个
// check for user
$user = $db->getUserByEmailAndPassword($username, $password);
if ($user != false) {
// user found
$response["status"] = "True";
$userID = $user["id"];
$response["users"]["id"] = $user["id"];
$response["users"]["name"] = $user["name"];
$response["users"]["email"] = $user["email"];
$result = mysqli_query($con1,"SELECT *
FROM friends
WHERE userID = '$userID'");
while($row = mysqli_fetch_array($result)) {
$response["users"]["friends"][] = $row;
}
}
echo json_encode($response);
答案 1 :(得分:0)
为什么,
之后还有额外的email
。
最后的元素不需要逗号。
<强>替换强>
{
"status": "True",
"users": {
"id": "16",
"name": "user",
"email": "user@example.com",
"friends": [
{
"id": "11",
"name": "frnd1",
"email": "frnd@example.com",//comma not needed here
},
{
"id": "12",
"name": "frnd2",
"email": "frnd@example.com",//here too
}
]
}
}
<强>与强>
{
"status": "True",
"users": {
"id": "16",
"name": "user",
"email": "user@example.com",
"friends": [
{
"id": "11",
"name": "frnd1",
"email": "frnd@example.com"
},
{
"id": "12",
"name": "frnd2",
"email": "frnd@example.com"
}
]
}
}