You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel将含键值对的JS文件转换为JSON文件?

在Laravel中实现JS到JSON的格式转换

1. 创建自定义Artisan命令

Laravel的Artisan命令适合处理这类文件转换任务,先生成命令文件:

php artisan make:command ConvertJsToJson

打开app/Console/Commands/ConvertJsToJson.php,替换为以下逻辑:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class ConvertJsToJson extends Command
{
    protected $signature = 'js:to-json {input} {output}';
    protected $description = '将导出式JS对象文件转换为标准JSON格式';

    public function handle()
    {
        $inputPath = $this->argument('input');
        $outputPath = $this->argument('output');

        // 校验输入文件是否存在
        if (!File::exists($inputPath)) {
            $this->error("输入文件 {$inputPath} 不存在");
            return 1;
        }

        // 读取并提取JS中的对象内容
        $jsContent = File::get($inputPath);
        preg_match('/export default\s*({.*})/s', $jsContent, $matches);
        
        if (!isset($matches[1])) {
            $this->error('无法从JS文件中提取有效对象');
            return 1;
        }

        // 补全键名的双引号,转为合法JSON结构
        $formattedObject = preg_replace('/(\w+):/', '"$1":', $matches[1]);
        
        // 解析并格式化JSON
        try {
            $jsonData = json_decode($formattedObject, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new \Exception('格式转换后JSON无效');
            }
            $jsonContent = json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            $this->error('JSON处理失败:' . $e->getMessage());
            return 1;
        }

        // 写入输出文件
        File::put($outputPath, $jsonContent);
        $this->info("转换完成:{$inputPath} → {$outputPath}");
        return 0;
    }
}

2. 执行转换命令

在终端运行命令,替换为你的实际文件路径:

php artisan js:to-json resources/lang/es.js resources/lang/es.json

注意事项

  • 确保待转换的JS文件仅包含export default导出的简单键值对对象,无复杂表达式或函数
  • 命令会自动处理键名补全引号、格式化缩进等细节,保留原始字符编码

内容的提问来源于stack exchange,提问作者gabogabans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:02:41