Why does this section of code generate extra brackets to the JSON object?

Viewed 35

The code in question:

    <?php

    $name = $_POST["name"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $email = $_POST["email"];
    
    writeToJSONFile($name, $username, $password, $email);

    function writeToJSONFile($name, $username, $password, $email){
        
        $currentData = file_get_contents("suckers.json");           
        $tempArray = array(json_decode($currentData, true));
        $toEncode = array("name"=>$name, "username"=>$username, "password"=>$password, "email"=>$email);            
        $tempArray[] = $toEncode;           
        $toWrite = json_encode($tempArray);         
        file_put_contents("suckers.json", $toWrite);
    }
?>

This is not meant to be some sort of secure json or website, it's just to learn php and other website making languages. The JSON will start empty, then after you run it once you get a json object, then running it a second time, it will add extra [] to the beginning and end of the old data.

1 Answers
function writeToJSONFile($name, $username, $password, $email){

    if(file_exists('suckers.json'))
        $currentData = json_decode( file_get_contents('suckers.json'), true );
    else
        $currentData = ['person_info' => null];

    $currentData['person_info'][] = array("name"=>$name, "username"=>$username, "password"=>$password, "email"=>$email);

    $toWrite = json_encode($currentData);
    file_put_contents("suckers.json", $toWrite);
}

check if file exists to avoid errors. Add person_info as key to the base array so it will properly stored/retrieved to/from a json file. Add true parameter in json_encode so it'll become array (json_encode returns stdClass Object by default). Add new data to the array.

Related