我正在開發一個Chrome擴展,在該擴展中,我使用jQuery將JSON發送到PHP文件,該文件將其寫入JSON文件。使用PHP從JSON對象中刪除第一個字符
我的jQuery的JSON對象:
var detailsArray = { title : [{
"title" : title,
"url" : url,
"username" : username,
"password" : password
}]
};
我的PHP代碼:
<?php
$dataToBeInserted = $_POST;
$file = "JSON.json";
//Open the file with read/write permission or show text
$fh = fopen($file, 'a+') or die("can't open file");
$stat = fstat($fh);
//Remove the last } character from the JSON file
ftruncate($fh, $stat['size']-1);
//Add the data from $dataToBeInserted to the file with a comma before it if there is data in file already.
if ($stat['size'] != 0) $append = ",";
echo fwrite($fh, $append . json_encode($dataToBeInserted,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
echo fwrite($fh, "}");
//Close the file
fclose($fh);
?>
我的JSON文件:
{
"Log In | Guild Wars 2" : [{
"url" : "https://account.guildwars2.com/login",
"username" : "Guildwars2isawesome",
"password" : "randompassword",
"title" : "Log In | Guild Wars 2"
}],
"library genesis" : [{
"url" : "http://gen.lib.rus.ec/",
"username" : "awesomesauce",
"password" : "applesauce",
"title" : "library genesis"
}],
"Google" : [{
"url" : "http://www.google.com",
"username" : "[email protected]",
"password" : "stackoverflowrules",
"title" : "Google"
}]
}
後,我的JSON添加到文件中,JSON變成這個:
{
"Log In | Guild Wars 2" : [{
"url" : "https://account.guildwars2.com/login",
"username" : "Guildwars2isawesome",
"password" : "randompassword",
"title" : "Log In | Guild Wars 2"
}],
"library genesis" : [{
"url" : "http://gen.lib.rus.ec/",
"username" : "awesomesauce",
"password" : "applesauce",
"title" : "library genesis"
}],
"Google" : [{
"url" : "http://www.google.com",
"username" : "[email protected]",
"password" : "stackoverflowrules",
"title" : "Google"
}]
,{
"title": [
{
"title": "jQuery.getJSON() | jQuery API Documentation",
"url": "http://api.jquery.com/jquery.getjson/",
"username": "",
"password": ""
}
]
}}
問題是,我在jQuery中編寫的JSON必須在對象的開頭有一個{
,以便在發送它時不會拋出錯誤。有什麼辦法可以刪除我正在寫入文件的對象的第一個{
,而不會破壞代碼?
刪除文件的最後一個字符並添加一個json字符串似乎不是生成json文件的非常可靠的方法。我只需讀取文件,將其轉換/解碼爲數組,然後添加所需的任何內容並編碼並寫入結果數組。 – jeroen
是不是很容易重新編譯成一個數組(因爲你正在使用php,'$ contents [] = $ dataToBeInserted'),然後''json_encode()''和'file_put_contents'到底 – user1978142