1 month ago

Deleting from a json file

Posted 1 month ago by Shiva

I have a json file that looks like this

        "product_1": {
            "category_1": "Category 1",
            "category_2": "Category 2"

What I'm trying to do is when I delete a category I want to remove the "key":"value" from the json file.

Here is my code

    public function deleteCategory($product, $category)
        $storage = storage_path("/products.json");
        $file = file_get_contents($storage);
        $json = json_decode($file);


        file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT));

        return (array)$json;

What happens is when I delete a category it doesn't remove it from the json.

And what I found strange was if I did this dd(file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT))) then it would work but if I only had file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT)) then it doesn't work. So I'm not sure where I'm going wrong.

Please sign in or create an account to participate in this conversation.