Gabotronix's avatar

Laravel: json_decode returns null

I'm trying to read the contents of a .js file in order to transform it into a .json file, however when I dd the result of json_decode I get null.

        // Parse the contents as JSON
        $data = json_decode($contents, true);
        //This returns null for some reason...
        dd($data);

This is how my .js file looks:

/templang/es.js

export default 
{
    currency:"€",
    void:"Vacio",
    filter : "Filtrar",
    filters : "Filtros",
    distance: " Distancia",
};

My full code:

        // Read the contents of the .js file
        $contents = File::get(base_path() . '/resources/templang/es.js');
        //I did a dd to confirm I'm getting the results back

        // Remove the "export default" line
        $contents = str_replace('export default', '', $contents);

        // Parse the contents as JSON
        $data = json_decode($contents, true);
        //This returns null for some reason...
        dd($data);

        // Write the data to the .json file
        $fileName = '/temp/transformed-'.rand(1,1000).'.json';

        Storage::disk('public')->put($fileName, json_encode($data, JSON_PRETTY_PRINT));

Thanks in advance!

0 likes
1 reply
LaryAI's avatar
Level 58

The issue is that the contents of the .js file are not valid JSON. The code is trying to parse the contents of the .js file as JSON, but it is not valid JSON. Instead, the contents of the .js file are in the format of a JavaScript object. To fix this, you can use a regular expression to extract the contents of the object and then use the json_encode function to convert it to JSON.

Here's an updated version of the code:

// Read the contents of the .js file
$contents = File::get(base_path() . '/resources/templang/es.js');

// Extract the contents of the object
preg_match('/{.*}/s', $contents, $matches);
$contents = $matches[0];

// Parse the contents as JSON
$data = json_decode($contents, true);

// Write the data to the .json file
$fileName = '/temp/transformed-'.rand(1,1000).'.json';
Storage::disk('public')->put($fileName, json_encode($data, JSON_PRETTY_PRINT));

The regular expression /{.*}/s matches everything between the first { and the last } in the file. The s modifier at the end of the regular expression allows the . character to match newlines.

Please or to participate in this conversation.