The "WordPress way" of making PHP values available to JavaScript is by enqueuing scripts and using wp_add_inline_script.
In your functions.php add an action hook for wp_enqueue_scripts. This hook is executed whenever scripts should be placed in the HTML.
In this hook you can register and enqueue scripts. That means we specify the files we need, and any dependency they have, for example jQuery, and couple an inline script with the PHP values to the JS file where we need the JSON in.
// Place me anywhere in functions.php.
add_action( 'wp_enqueue_scripts', function() {
// Get all the products.
$products = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
) );
// Turn the products into a JSON string.
$products_json = json_encode( $products );
// Register your script.
// Check if the path to your JS file is correct.
// get_theme_file_uri looks relative to the style.css file.
wp_register_script( 'products', get_theme_file_uri( '/js/products.js' ), [], '1.0.0', true );
// Add the inline script where the PHP data is turned into JavaScript.
wp_add_inline_script( 'products', "window.__products__ = $products_json", 'before' );
// Place both scripts in the HTML.
wp_enqueue_script( 'products' );
} );
Now this specific function outputs an inline script <script>...</script> before a script with <script id="products-js" src="https://yoursite/path-to-script/main.js"></script>
The inline script creates a property on the window object which can be accessed from any file (as long as the file comes after the creation of the property).
// products.js file.
var products = window.__products__;
console.log(products);