gpt4 book ai didi

json - 无法在laravel中读取json文件

转载 作者:行者123 更新时间:2023-12-04 07:29:08 29 4
gpt4 key购买 nike

我正在尝试创建一个简单的 laravel crud,在那里我将能够使用 json 文件作为数据库而不是 MySQL。但是当我尝试从位于“resource/lang”文件夹中的 json 文件中获取数据时,它返回“null”。
输出是:
Please click to view the Image
我的 Controller 代码:

    public function getjson(){

$json = file_get_contents('../resources/lang/test.json');
$gravatar = json_decode($json);
dd($gravatar);
}
我的 json 文件(位于 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",
},
]
来自 web.php 的路由是:
Route::get('/getjson', 'App\Http\Controllers\Master@getjson');
test.json file screenshot
dd($json result screenshot)

最佳答案

问题在于 test.json 中的 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"
}
]
在总价和最后一个对象结束后删除不需要的逗号。用于多语言用途的语言文件夹。所以我建议你使用存储文件夹来保存这个文件
用于访问存储文件 storage/app/test.json
$json = \Illuminate\Support\Facades\Storage::get("test.json");
$gravatar = json_decode($json);
dd($gravatar);
更新
正如@shaedrich 的上述评论。
检查 JSON 错误
$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;
}

关于json - 无法在laravel中读取json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68046100/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com