search

Home  >  Q&A  >  body text

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

I have a question about using PHP with JSON.

I use array to store inside .json file. The array containing the data comes from my index.php and is populated by the user, so far so good. Everything is saved in .json and when I have more than 1 user storing content in it (meaning there are 2 arrays in the .json file), it does not return the data but returns NULL. Am I missing something about saving or reading a JSON file? I found that my JSON was invalid, it was showing me "Multiple root JSON elements" inside the validator.

This is my code for writing and reading .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 like this (2 arrays populated):

[{"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 populate the array and then pass it to the JSONwrite method (this is inside the foreach loop):

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

    }

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

Is there a way to validate it like this so that decoding doesn't return null?

P粉333395496P粉333395496309 days ago449

reply all(1)I'll reply

  • P粉724256860

    P粉7242568602024-02-18 00:20:20

    An array under another array is invalid JSON. You should use a root array and keep your users in it (not sure if what's in the array makes 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 look like this:

    1. User sends form
    2. You have read the file content
    3. You can decode it using json_decode()
    4. You add to the array
    5. You can use json_encode() to encode it back
    6. You save the entire new JSON to the file, replacing the old content

    reply
    0
  • Cancelreply