Can I use a JSON file as a database?

2

I want to start a project, however I do not want to create a database so I would like to know if I could use a json file as a database.

    
asked by anonymous 03.05.2018 / 01:50

2 answers

2

You can do this with the file functions a example recording :

// Array com dados
$cliente1 = array(
    'codigo'   => '001',
    'nome'     => 'William',
    'telefone' => '012 9999-6352'
);

$cliente2 = array(
    'codigo'   => '002',
    'nome'     => 'Adriano',
    'telefone' => '012 8888-4452'
);

$cliente3 = array(
    'codigo'   => '003',
    'nome'     => 'Maria',
    'telefone' => '013 3434-4444'
);

// Atribui os 3 arrays para apenas um array
$dados = array($cliente1, $cliente2, $cliente3);

// Tranforma o array $dados em JSON
$dados_json = json_encode($dados);

// Cria o arquivo cadastro.json
// O parâmetro "a" indica que o arquivo será aberto para escrita
$fp = fopen("cadastro.json", "a");

// Escreve o conteúdo JSON no arquivo
$escreve = fwrite($fp, $dados_json);

// Fecha o arquivo
fclose($fp);

And an example of reading :

// Para o PHP 5 e superior
$handle = fopen("cadastro.json", "rb");
$contents = stream_get_contents($handle);
fclose($handle);

var_dump(json_decode($contents));

You can also assign the json of the file to a javascript variable and work with it on the front end, in that case do not use json_decode :

//...
echo "<script> let json = $contents; </script>";

But I believe you are "thinking wrong" if you want to do something simpler using a json file and then not have to change the bank structure, business rules, etc. I suggest you just do the view part, validate it, and then go back to the back end. To make such a system and then change the database from a json file to a SQL model will give much more work, it is preferable to keep the same structure (no-sql), perhaps just changing from json files to some bank like MongoDB or Firebase Realtime Database

    
03.05.2018 / 02:52
0

The default configuration data for a system module I am developing is being saved in the .json database. So in general, yes, you can use ... Tip 1: If you have PHP, build a class to manage the CRUD of the data in .json files used as DB. Tip 2: Create / edit a .htaccess (or create in the top directory of .json files), to prevent directory / file listing this avoids listing the .json files used as DB. Also in .htaccess, configure to prevent access to the .json files folder or direct access to your db.json file (for example), so that third parties can not access your .json directly from the browser (for example) and only your server you will have access or your previously created PHP class. To improve the experience, do it in AJAX.

    
04.12.2018 / 18:54