Benjamin Benjamin - 2 months ago 7
Javascript Question

Writing Json to existing file .json without "syntax errors"

This one may be a tad tricky to understand if I'm not clear. I want to open a

.json
file, which contains an
array
and add/
append
to that
array
but I keep coming into format problems with the
array
. I first thought this needed to be PHP but I don't see why it couldn't be JS now.

Some may ask, why aren't I using a database, it just won't work for what I want to do. I just what to store data in a file on-site without a database.

analytics.php on execution adds the data to the data.json file. The plan is to call this on every visit (small site).

$visitArray = [];

$visitArray["ip"] = "127.0.0.1";
$visitArray["referrer"] = "www.google.com";
$visitArray["conversion"] = "nil";
$visitArray["bounce"] = "nil";
$visitArray["platform"] = "Chrome";
$VisiterArray[] = $visitArray;



$data = json_encode($VisiterArray);
$data = $data;
file_put_contents("data.json", $data, FILE_APPEND);


data.json (when analytics.php is executed)

[
{
"ip":"127.0.0.1",
"referrer":"www.google.com",
"conversion":"nil",
"bounce":"nil",
"platform":"Chrome"
}
]


The problem is if you run the analytics.php there's no "," and I don't think it's as easy to solve to change
$data = $data;
to
$data = $data.',';
it just seems like a terrible way to do things.

[
{
"ip":"127.0.0.1",
"referrer":"www.google.com",
"conversion":"nil",
"bounce":"nil",
"platform":"Chrome"
}
]
// missing ","
[
{
"ip":"127.0.0.1",
"referrer":"www.google.com",
"conversion":"nil",
"bounce":"nil",
"platform":"Chrome"
}
]

Answer

What you want to do isn't easily achievable, as just adding a ',' would also result in invalid json (as your arrays would also need to be in an array)

Easiest solution would be just unserialise your JS and append it there. Something like

$VisiterArray = json_decode(file_get_contents("data.json"));
$visitArray = [];

$visitArray["ip"] = "127.0.0.1";
$visitArray["referrer"] = "www.google.com";
$visitArray["conversion"] = "nil";
$visitArray["bounce"] = "nil";
$visitArray["platform"] = "Chrome";
$VisiterArray[] = $visitArray;

$data = json_encode($VisiterArray);
file_put_contents("data.json", $data);

Although this isn't really ideal for logging.

If you really did want to do it that way, you could probably kinda cheat. Ie. append a "," after each entery like you suggested, then read it with something like $data = json_decode("[".file_get_contenst("data.json")."]"); which may work - although the file isn't really json at this point, so its a little hacky/nasty IMO. As others have suggested, a standard log file format probably makes more sense.