使用PHP从JSON对象中删除第一个字符
我正在开发一个Chrome扩展,在这个扩展中,我使用jQuery将JSON发送到一个PHP文件,该文件将JSON写入一个JSON文件 我的jQuery JSON对象:使用PHP从JSON对象中删除第一个字符,php,jquery,json,Php,Jquery,Json,我正在开发一个Chrome扩展,在这个扩展中,我使用jQuery将JSON发送到一个PHP文件,该文件将JSON写入一个JSON文件 我的jQuery JSON对象: var detailsArray = { title : [{ "title" : title, "url" : url, "username" : username,
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添加到文件后,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必须在对象的开头有一个
{
,才能在我发送它时不抛出错误。有没有办法在不破坏代码的情况下删除我正在写入文件的对象的第一个{
json_encode($dataToBeInserted..)。
转换为字符串时,删除第一个{和最后一个}删除文件的最后一个字符并添加json字符串似乎不是生成json文件的一种非常可靠的方法。我只需读取文件,将其转换/解码为数组,添加所需的任何内容,并对结果数组进行编码和写入。重新生成数组不是更容易吗(因为您使用的是php,
$contents[]=$dataToBeInserted
),然后再次使用json\u encode()
,并将file\u contents
放在末尾,我不知道如何做。我想我需要使用substr($dataToBeInserted,1,-1);
但我应该把它放在哪里?我对php一无所知,我可以使用帮助xD
{
"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": ""
}
]
}}