Rodrigo Cabrera
Rodrigo Cabrera

Reputation: 164

creating valid json data in Laravel

When a new User is created, I save the username and password (no hashed) in a json file as well as in the DB, so every time I'm appending new users to the json file:

{
  "user3": "demo"
} {
  "user4": "demo"
} {
  "user4": "demo"
} {
  "user5": "demo"
}

the code:

$data = array($request->input('username') => $request->input('password'));
            $datos = json_encode($data);
            File::append(storage_path('archivos/datos.json'), $data);

of course the format above isn't valid json, how could i get this

[{
"user3": "demo"
}, {
"user4": "demo"
}, {
"user4": "demo"
}, {
"user5": "demo"
}, {
"user5": "demo"
}, {
"user5": "demo"
}, {
"user7": "demo"
 }, {
"user8": "demo"
 }]

and read it using foreach like this:

$result = File::get(storage_path('archivos/datos.json'));
$result = json_decode($result);
foreach($result as $key=>$item){
   echo $key .''. $item;
} 

Upvotes: 0

Views: 107

Answers (2)

cre8
cre8

Reputation: 13562

the fastest way would be to append some data:

fopen('myfile.json', 'a');

but you want to store an array, so you have to read the content of the file, update it and save it.

$users = json_decode(file_get_content(storage_path('archivos/datos.json')));

$users[] = $newUser;

file_put_contents(storage_path('archivos/datos.json'), json_encode($users, JSON_PRETTY_PRINT);

you can also make a one-liner (ugly, but works):

file_put_contents(storage_path('archivos/datos.json'), json_encode(json_decode(file_get_content(storage_path('archivos/datos.json')))[] = $newUser, JSON_PRETTY_PRINT);

Upvotes: 0

Roham Shojaei
Roham Shojaei

Reputation: 470

First get the string from file then you can do a str_replace all "} {" with "} , {" a json also have [ at the start and ] at the end so we add them too:

$json = "[".str_replace('} {', '},{', $fileContent)."]";

Here we have a json string in $json variable so we can convert it to array by this:

$users = json_decode($json);

Upvotes: 1

Related Questions