0

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;
} 
3
  • 1
    If you want to append to a JSON array in a file, you'll need to decode and re-encode it each time. Commented Aug 30, 2017 at 17:01
  • should i use array_push then? Commented Aug 30, 2017 at 17:13
  • 1
    Also, may I STRONGLY suggest not to store plain-text passwords? Commented Aug 30, 2017 at 17:28

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think this is the problem he needs to solve. The OP's first code snippet, which you're addressing here, was just an example of the results of his current attempt.
What I think he want is get none json string from a file as json it's not possible, Also every time reading the file decoding and adding new user to the array then writing this in file it's not a good idea because for every user we have to do this it's not good for performance
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.