使用PHP从JSON对象中删除第一个字符

时间:2014-06-18 01:03:19

标签: php jquery json

我正在开发一个Chrome扩展程序,在其中我将带有​​jQuery的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" : "someone@gmail.com", 
    "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" : "someone@gmail.com", 
    "password" : "stackoverflowrules",
    "title" : "Google"
}]
,{
    "title": [
        {
            "title": "jQuery.getJSON() | jQuery API Documentation",
            "url": "http://api.jquery.com/jquery.getjson/",
            "username": "",
            "password": ""
        }
    ]
}}

问题是我在jQuery中编写的JSON必须在对象的开头有一个{,以便在我发送它时不会抛出错误。有没有办法删除我写入文件的第一个{对象,而不会破坏代码?

1 个答案:

答案 0 :(得分:0)

您再次添加整个对象 json_encode($ dataToBeInserted ..)。 转换为字符串时,删除$ dataToBeInserted的第一个{和最后一个}。