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 파일 : 나는 파일에 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이된다 이 :
{
"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는 배열을 다시 작성하는 것이 쉽지 않습니다. (PHP에서'$ contents [] = $ dataToBeInserted'를 사용하고 있기 때문에), 마지막에'json_encode()'와'file_put_contents'를 다시 말입니다. – user1978142