Home > Blockchain >  json_decode returns null after storing 2 arrays in .json file - validation
json_decode returns null after storing 2 arrays in .json file - validation

Time:06-07

i have a question regarding PHP in combination with JSON.

Im using an array to store inside of a .json file. The array which has the data for it comes from my index.php and is getting filled up by the user, so far so good. Everythings saving inside the .json, just when i have more than 1 user storing stuff in it (meaning having 2 arrays inside the .json file) it doesnt return me the data, instead it is returning me NULL. Am i missing something regarding the saving or reading of the JSON file? I figured out that my JSON is invalid and it's showing me "Multiple Root JSON elements" inside the validator.

Here my code of writing and reading the .json:

public function JSONwrite($lists)
    {
        $listFill = json_encode($lists)."\n";
        file_put_contents("/var/www/html/3sprint/test.json",$listFill,FILE_APPEND);
    }

    public function JSONread()
    {
        $string = file_get_contents("/var/www/html/3sprint/test.json");
        $stringContent = json_decode($string, true);
        var_dump($stringContent);
    }

My JSON file looks something like this (filled with 2 arrays):

[{"count":"3","name":"testnameone"},{"count":"5","name":"testnametwo"},{"count":"6","name":"testnamethree"},{"info":106}]
[{"count":"3","name":"testnamefour"},{"count":"5","name":"testnamefive"},{"count":"6","name":"testnamesix"},{"info":521}]

This is where i fill my array, before passing it to the JSONwrite method (this is inside a foreach loop):

           $lists[]= [
                "count"=>$count,
                "name"=>$name
            ];
        }

    }

    $lists[]= [
        "info" => $number
    ];

Is there a way i can validate it now just like this so the decode won't return null?

CodePudding user response:

One array under another is invalid JSON. You should use one root array and keep your users inside it (not sure if the contents inside the arrays make sense, but you get the idea):

[
    [{"count":"3","name":"testnameone"},{"count":"5","name":"testnametwo"},{"count":"6","name":"testnamethree"},{"info":106}]
    [{"count":"3","name":"testnamefour"},{"count":"5","name":"testnamefive"},{"count":"6","name":"testnamesix"},{"info":521}]
]

In other words, it should go as follows:

  1. User sends the form
  2. You read the contents of the file
  3. You decode it with json_decode()
  4. You add to the array
  5. You encode it back with json_encode()
  6. You save entire new JSON to the file, replacing the old contents
  • Related