Can't read json file in laravel

Viewed 703

I am trying to create a simple laravel crud, where I will be able to use a json file as database instead of MySQL. But it's returning "null" when I am trying to fetch data from the json file located in "resource/lang" folder .

The output is :

Please click to view the Image

My codes from controller :

    public function getjson(){

    $json = file_get_contents('../resources/lang/test.json');
    $gravatar = json_decode($json);
    dd($gravatar);
   }

My json file (locating at resources/lang/test.json)

[
{   
    "id": 1,
    "product_name": "Apple",
    "per_item_price": "10",
    "product_quanity": "4",
    "total_price": "50",
},

{
  
    "id": 2,
    "product_name": "Apple",
    "per_item_price": "10",
    "product_quanity": "4",
    "total_price": "50",
},
]

And The route from web.php is :

Route::get('/getjson', 'App\Http\Controllers\Master@getjson');

test.json file screenshot

dd($json result screenshot)

1 Answers

The issue is with JSON in test.json. Because it has a trailing comma.

[
    {
        "id": 1,
        "product_name": "Apple",
        "per_item_price": "10",
        "product_quanity": "4",
        "total_price": "50"
    },

    {

        "id": 2,
        "product_name": "Apple",
        "per_item_price": "10",
        "product_quanity": "4",
        "total_price": "50"
    }
]

Remove unwanted comma after total price and end of last object. Language folder used for multi-language purpose. So I suggest you to use storage folder to save this file

For accessing storage files storage/app/test.json

$json = \Illuminate\Support\Facades\Storage::get("test.json");
    $gravatar = json_decode($json);
    dd($gravatar);

Updated As above comment by @shaedrich.

To check JSON error

$json = \Illuminate\Support\Facades\Storage::get("test.json");
    $gravatar = json_decode($json);
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
            break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
            break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
            break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
            break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
        default:
            echo ' - Unknown error';
            break;
    }
Related