【发布时间】:2019-01-05 23:20:18
【问题描述】:
所以我需要将数据原样添加到我的 JSON 中。
预期的 JSON
"users": [
{
"username": "admin",
"password": "admin",
"isAdmin": true
},
{
"username": "bleh",
"password": "meh",
"isAdmin": false
}
]
相反,我得到:
"users": [
{
"username": "admin",
"password": "admin",
"isAdmin": true
},
{
"username": "bleh",
"password": "meh",
"isAdmin": false
},
"{\"isAdmin\":false,\"username\":\"test1\",\"password\":\"$2y$10$fSb.0bw\\\/MbtBx.PHerRdU.gahYnRezZZuy8VYL41ah8YwPxW6hOTq\"}"
]
我对这个问题失去了理智,因为我找不到找到我的代码的哪一部分将额外的引号和反斜杠添加到添加的字符串的方法。
这是我的 php 代码,负责向 JSON 添加值:
if (self::checkExistence($this->username) == true){
return false;
}
$newUserJson = json_encode($this);
$inp = file_get_contents(getcwd() . self::USERS_LOCATION);
$tempArray = json_decode($inp,true);
array_push($tempArray["users"], $newUserJson);
$jsonData = json_encode($tempArray);
file_put_contents(getcwd() . self::USERS_LOCATION, $jsonData);
return true;
我知道使用文件而不是数据库并不是“最佳实践”,但现在使用文件就足以满足我的需求,因此请不要评论“使用 db 代替”之类的内容。
【问题讨论】:
标签: php json array-push