Error in syntax JSONLoader

I am attempting to bring my models from Cinema 4D into three.js. I have used the OBJLoader successfully. If I try to convert my exported wavefront (.obj) file with convert_obj_three.py, it generates a json-file without any errors.

However, when I try to load the resulting .js-file in my three.js script, I encounter this error:

Uncaught SyntaxError: Unexpected token ;

This is what I have attempted so far:

var loader2 = new THREE.JSONLoader();
loader2.load('assets/models/test.js', createScene);
function createScene(){
    mesh = new THREE.Mesh();
    scene.add(mesh);
}

test.js:

Error screenshot:

You can find the entire code below:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - loaders - OBJ loader</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                font-family: Monospace;
                background-color: gray;
                color: #fff;
                margin: 0px;
                overflow: hidden;
            }
            #info {
                color: #fff;
                position: absolute;
                top: 10px;
                width: 100%;
                text-align: center;
                z-index: 100;
                display:block;
            }
            #info a, .button { color: #f00; font-weight: bold; text-decoration: underline; cursor: pointer }
        </style>
    </head>

    <body>
        <div id="info">
        <a href="http://threejs.org" target="_blank">three.js</a> - OBJLoader test
        </div>

        <script src="assets/three.min.js"></script>
        <script src="assets/OBJLoader.js"></script>

        <script src="assets/TrackballControls.js"></script>

        <script src="assets/Detector.js"></script>
        <script src="assets/stats.min.js"></script>

        <script>

            var container, stats;

            var camera, scene, controls, renderer;

            var mouseX = 0, mouseY = 0;

            var windowHalfX = window.innerWidth / 2;
            var windowHalfY = window.innerHeight / 2;


            init();
            animate();


            function init() {

                container = document.createElement( 'div' );
                document.body.appendChild( container );

                camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
                camera.position.z = 900;

                // controls

                controls = new THREE.TrackballControls( camera );

                controls.rotateSpeed = 5.0;
                controls.zoomSpeed = 5;
                controls.panSpeed = 2;

                controls.noZoom = false;
                controls.noPan = false;

                controls.staticMoving = true;
                controls.dynamicDampingFactor = 0.3;

                // scene

                scene = new THREE.Scene();

                var ambient = new THREE.AmbientLight( 0xfff3dd );
                scene.add( ambient );

                var directionalLight = new THREE.DirectionalLight( 0xffeedd );
                directionalLight.position.set( 0, 0, 1 ).normalize();
                scene.add( directionalLight );

                // model

                var loader2 = new THREE.JSONLoader();
                loader2.load('assets/models/test.js', function (geometry, materials){

                    mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
                    scene.add(mesh);

                });

                renderer = new THREE.WebGLRenderer();
                renderer.setSize( window.innerWidth, window.innerHeight );
                container.appendChild( renderer.domElement );
                window.addEventListener( 'resize', onWindowResize, false );

            }

            function onWindowResize() {

                windowHalfX = window.innerWidth / 2;
                windowHalfY = window.innerHeight / 2;

                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();

                controls.handleResize();
                renderer.setSize( window.innerWidth, window.innerHeight );

            }

            function animate() {

                requestAnimationFrame( animate );
                render();

            }

            function render() {

                controls.update();
                renderer.render( scene, camera );

            }

        </script>
    </body>
</html>

Answer №1

How to implement a function for loading JSON files:

Implementing the THREE.JSONLoader.prototype.load = function ( url, callback, texturePath )



loader2.load('assets/models/test.js', function(geometry, materials){

   mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
   scene.add(mesh);

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining metadata from Youtube videos with Javascript and HTML5

Is there a way to fetch YouTube video data with Javascript and HTML5? If so, could you provide some helpful resources or links? ...

"Strategies for disabling navigation in a React single-page application when a user manually inputs a page href with React Router v6

Our application is built with Single Page Application (SPA) architecture and we utilize react router v6 for handling navigation. We have a scenario where each page has a specific set of restricted URLs which users should not be able to access directly by ...

Leverage the power of getServerSideProps when working with Dynamic Routes

I have been working on implementing getServerSideProps in my file named [username].js which utilizes dynamic routing. Next.js requires the use of both getStaticPaths() and getStaticProps({ params }) for dynamic routing. However, there seems to be an issu ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...

Calculating the screen-space coordinates for FBO value retrieval using a depth texture

EDIT: I have updated the JSFiddle link because it was not displaying correctly in Chrome on Windows 7. Situation I am experimenting with particles in THREE.JS and utilizing a frame buffer / render target (double buffered) to write positions to a texture. ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

Extract Data from JSON Array using Jquery

I am working with a JSON array retrieved from a web API, and I need to extract specific values from it. For instance, how can I retrieve all the rides in the first place and access rides[1]. UserID or Images? { "Status":1, "Rides& ...

Failure to highlight items when using the multiple select function

After adding a select all button to a multiple select, I encountered an issue. Although all the items are being selected, they are not highlighted when clicking on the select all button. Below is the code snippet: <div class="label_hd">Profiles* {{ ...

Issue: React child objects are not acceptable (detected: object containing keys {inputList}). To display a group of children, please utilize an array instead

My attempt at creating input fields using key and value pairs has hit a roadblock. Despite thinking it would be straightforward, I am encountering an error that is proving tricky to resolve. import {Form, Input, Button } from 'semantic-ui-react' ...

Bookshelfjs fails to return a promise when updating multiple data

I am facing an issue when trying to update multiple rows in my database. The problem lies in the fact that the promise does not return anything, even though the data is successfully saved. Below is a snippet of my code: doUpdate: Promise.method(function ...

Performing Ajax requests WHILE another Ajax call is ongoing to retrieve the server's task completion status and present it to the user as a loading bar

I am currently exploring the possibility of obtaining the completion status of a task (initiated through an ajax call) by using multiple ajax calls at timed intervals. Essentially, while a lengthy process is being executed, I aim to store a variable and re ...

What is the best way to store the input value within a variable?

I am developing a new component that includes an input field and a button. The user is required to enter their nickname in the input field. This nickname, captured as the input value, needs to be stored in a variable. This variable is integral to a functio ...

Tips and tricks for displaying a confirmation modal prior to a user switching to another tab

In my application, I have a section designed with Bootstrap 4 tabs. There are six tabs, and five of them contain forms with input fields. The original code was submitting all data (for all 5 out of 6 tabs) at once. This approach seemed unnecessary to me si ...

Sending compressed JSON data to the browser live

Seeking help with converting JSON streaming to pass through a custom GZIPFilter I have implemented. After tweaking the filter to flush as needed, the output seems to be generating compatible gzip browser data. However, when I redirected the output to a fil ...

The form's validation fails to recognize dynamically added input after the initial validation

I am currently working on a form that dynamically adds inputs. Whenever the user selects a different "supplier" from the addMaterialSupplier dropdown, a new input for the price is automatically added. The issue I'm facing is that when I click the bu ...

Use a JSON file to dynamically define the file path for static assets in the index.html file of a React application

I am working on a solution to dynamically modify the file paths of static files (js & css) in the index.html file within my create-react-app. My goal is to have these paths directed to different sub-directories based on settings specified in a settings.jso ...

d3 bar chart with overlapping bars - define x and y coordinates

Here is a glimpse of the data I am working with: var students = [ {'race': 'Black', 'count': 7, 'year': 2004, 'allnames': ['G Brown', 'F Clarkson', 'E Miller', 'R Black& ...

Waiting for response in AngularJS Controller and setting callback

I have developed an AngularJS application with controllers.js and factories.js that I am excited about. However, I am facing a challenge when trying to manipulate the values within the controller (retrieved from the factories). The issue is that these val ...

How can I use JQuery to iterate through Object data and dynamically create tr and td elements?

In previous projects, I utilized Vanilla JS to iterate through Ajax return data and construct tables. However, for this current project, I have decided to switch over to JQuery. The main reason behind this decision is that some of the td elements require s ...

Quickly block all paths in Express

Attempting to implement var _LOCK_ = true; // either set it manually or load from configuration settings app.all('*', function(req,res,next){ if(_LOCK_) return res.send(401); next(); }); // other routes go here app.get(...); app.post(... ...