如何将JSON文件加载到Laravel控制器?

8
我有一个JSON文件,想将其加载到Laravel控制器中,以便在我的应用程序中使用数据。

该文件的路径为/storage/app/calendar_Ids.json。

正确的操作方式是什么?

4个回答

20

这里,这应该有助于你进行分类。

use Storage;

$json = Storage::disk('local')->get('calendar_Ids.json');
$json = json_decode($json, true);

刚看到你在底部的编辑,这对我来说完美地解决了问题。谢谢! - Zach Tackett

5

试试这个

$path = '/storage/app/calendar_Ids.json';
$content = json_decode(file_get_contents($path), true);`

然后只需dd($content);,查看它是否有效。

这对我有效,但您知道是否有使用Laravel特定的方法来做吗? - Zach Tackett

1
你也可以尝试这个方法:
 $json = file_get_contents('your json file path here.....');

//converting json object to php associative array
$data = json_decode($json, true);

foreach($data as $item){

   
        DB::table('table name')->insert(
            array(
                    
                   'clientId'     =>   $item['clientId'], 
                   'socialMediaLinkId'   =>   $item['socialMediaLinkId'],
                   'link'   =>   $item['link'],
                   'isEnabled'   =>   $item['isEnabled'],
                   'created_at'   =>   $item['created_at'],
                   'updated_at'   =>   $item['updated_at'],
                   'isSelectedByDefault'   =>$item['isSelectedByDefault'],
                   'showOnNegativePage'   =>$item['showOnNegativePage']
        
        
            )
        );
    }

-1

您也可以尝试这个:

$json = storage_path('folder/filename.json');

这只是在资源目录中生成给定文件的完全限定路径,不读取文件内容。 - Nik Sumeiko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接