Save a JSON file inside square brackets and separated by comma

Asked

Viewed 605 times

3

I’m trying to save a file dados.json, where the form data is sent via POST to a file dados.php by AJAX.

The code of dados.php is as follows:

$array = array();
$fp = fopen("dados.json", "a");
$escreve = fwrite($fp, $array[0] = json_encode($_POST));
fclose($fp);

The structure of the data that the dados.php generates for the dados.json is:

{"nome":"fulano","numero":"1"}

The problem is that I wanted to make a structure in which these data sent were inside brackets and that at the end of each key had a comma, but every time I send the data, they are saved in the dados.json is generated like:

{"nome":"fulano","numero":"1"}{"nome":"fulano2","numero":"3"}

It is not separated by comma. I tried otherwise with the following code:

$array = array($_POST);
$jsonDados = json_encode($array);
$fp = fopen("dados.json", "a");
$escreve = fwrite($fp, $jsonDados);
fclose($fp);

But now the dados.json was like this:

[{"nome":"fulano","numero":"1"}][{"nome":"fulano2","numero":"3"}]

I just want to make this data saved like this:

[{"nome":"fulano","numero":"1"},{"nome":"fulano2","numero":"3"}]

And that every time there is a submission form to the dados.php, it saves JSON by separating keys by commas inside the brackets.

3 answers

0

If you want in this format:

[{"nome":"fulano","numero":"1"},{"nome":"fulano2","numero":"3"}]

Then you have to generate an array, in which each element is one of the objects containing the name and number. Because according to the syntax of JSON format, the brackets are used to delimit an array (see more details here).

But then we have to evaluate how to do it. Let’s assume that the current content of the file is this:

[{"nome":"fulano","numero":"1"}]

If the idea is to add another element in the same JSON array, we cannot simply concatenate at the end. Because what we want is for it to be the same as the first JSON above (that is, all the elements inside the brackets, and separated by comma).

Thus, a solution would be to read the file, do JSON’s Parsing (generating an array), add the data in that array, convert back to JSON, and write to the file:

$arquivo = 'dados.json';
if (file_exists($arquivo)) { // arquivo existe, lê o conteúdo e faz o parsing do JSON
    $json = json_decode(file_get_contents('dados.json'), true);
} else { // arquivo não existe, começa com um array vazio
    $json = [];
}

// adiciona os dados no JSON array
$json[] = $_POST;

// escreve no arquivo
file_put_contents($arquivo, json_encode($json));

So, the first time (when the file does not yet exist) will be written to it:

[{"nome":"fulano","numero":"1"}]

The second time you receive data, this file will be read and json_decode will perform the Parsing of that content, generating an array. Then we add the new content in this array, we use json_encode to convert it to JSON and write it to the file. The result will be:

[{"nome":"fulano","numero":"1"},{"nome":"fulano2","numero":"3"}]

And so on. With each new call, a new element is added to the array, for example:

[{"nome":"fulano","numero":"1"},{"nome":"fulano2","numero":"3"},{"nome":"fulano3","numero":"42"}]

Of course this can be making a problem in the future as the file gets big. In this case, you may need to something like that. Or, if it comes to a considerable amount of data, maybe it is better to use a database. But then we are already running too far from the scope...

-1

You can do it this way:

$dados = json_decode(file_get_contents ("dados.json"));
array_push($dados, $_POST);
$fp = fopen("dados.json", "a");
fwrite($fp, json_encode($dados));
fclose($fp);
  • ok, but the result on the.json data will always be {"nome":"fulano","numero":"1"} and every time the data is sent from the form will be saved in sequence ex {"nome":"fulano","numero":"1"}{"nome":"fulano","numero":"1"} i wanted a structure in which every time there is a submission of the form to the.php data, it saves the json by separating the keys by commas inside the brackets, as I mentioned in the question, there is a way to do this?

  • I changed the answer

-1

I usually use old solutions, then I refine the code, for your case I would do so:

<?php
    
    $dados = file_get_contents("dados.json");
    
    $dados = substr($dados, 0, strlen($dados) - 1) . ",";
    
    // Simulando $_POST
    
    $POST = array();
    $POST[] = array("nome" => "fulano1", "numero" => "1");
    $POST[] = array("nome" => "fulano2", "numero" => "2");
    $POST[] = array("nome" => "fulano3", "numero" => "3");
    $POST[] = array("nome" => "fulano4", "numero" => "4");
    
    foreach ($POST as $key) {
        $dados .= json_encode($key) . ",";
    }
    
    $dados = substr($dados, 0, strlen($dados) - 1) . "]";
    
    file_put_contents("dados.json", $dados);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.