ThreeJS is having trouble loading JSON files

After reading through this particular question, I unfortunately did not find the help I was seeking.

Here's my process: First, I export a model from Cinema 4D to .obj format. Then, I import the obj file into www.threejs/editor.

I fill in all the necessary information.

Next, from the scene tree, I select my object and export it as a Three.js Object, which saves as a .json file.

Here is the snippet of my code:

<script>
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
var object3D = new THREE.Object3D(), loader = new THREE.JSONLoader(true);
loader.load( "brikk2.json", function ( geometry, materials ) {
    var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: 0xff0000, ambient: 0xff0000 } ) );
    scene.add( mesh );
}); 
           var render = function () {
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    };
    render();
</script>

Upon running this code, I encountered the following error messages:

THREE.WebGLRenderer 67                             three.js:20806
THREE.WebGLRenderer: elementindex as unsigned integer not supported.         three.js:26942
XHR finished loading: "http://xxxxxx.xx/tst/mrdoob-three2/brikk2.json".     three.js:12018
    THREE.JSONLoader.loadAjaxJSON                  three.js:12018
    THREE.JSONLoader.load                          three.js:11942
    load                                           test.html:23
     (anonymous function)                          test.html:28
 Uncaught TypeError: Cannot read property 'length' of undefined             three.js:12087
    parseModel                                                      three.js:12087
    THREE.JSONLoader.parse                                          three.js:12028
    xhr.onreadystatechange                                          three.js:11969

This is the structure of the JSON file I loaded:

{
"metadata": {
    "version": 4.3,
    "type": "Object",
    "generator": "ObjectExporter"
},
"geometries": [
    {
        "uuid": "213E28EF-E388-46FE-AED3-54695667E086",
        "name": "brikkG",
        "type": "Geometry",
        "data": {
            "vertices": [0.036304,-0.016031,-0.027174,0.036304,0.......


      ........ 232,1228,1139,1141,1140,1]
        }
    }],
"materials": [
    {
        "uuid": "F74C77E4-8371-41BC-85CA-31FC96916CC6",
        "name": "lego",
        "type": "MeshPhongMaterial",
        "color": 16721408,
        "ambient": 16777215,
        "emissive": 0,
        "specular": 16777215,
        "shininess": 30,
        "opacity": 1,
        "transparent": false,
        "wireframe": false
    }],
"object": {
    "uuid": "3BAAB8CA-1EB7-464A-8C6D-FC4BBB3C63C6",
    "name": "BrikkM",
    "type": "Mesh",
    "geometry": "213E28EF-E388-46FE-AED3-54695667E086",
    "material": "F74C77E4-8371-41BC-85CA-31FC96916CC6",
    "matrix": [1000,0,0,0,0,1000,0,0,0,0,1000,0,0,0,0,1]
      }
     }

I have exhausted all my efforts trying different methods to import native JSON into Three.js, using files from both the Three.js Editor and clara.io. Unfortunately, I keep encountering the same error message and I am completely at a loss after spending 3 days attempting to rectify this issue.

If I attempt to create geometry like CubeGeometry, it renders without any issues. However, as soon as I try to work with native JSON objects, nothing seems to work anymore.

Can someone lend me a hand?

Answer №1

Alright, I discovered the solution over at:

The original JSON code is actually perfect; it just needs to be loaded using ObjectLoader instead of JSONLoader (don't confuse it with OBJLoader like I did in one of my experiments). JSONLoader is designed for loading JSON data with a specific format/structure, while ObjectLoader is meant for loading native data that is also written in JSON but follows a different structure/format.

Therefore, use this:

var loader = new THREE.ObjectLoader();
loader.load( 'brikk2.json', function ( object ) {

            scene.add( object );

} );

and it will work successfully.

Here's a complete example code snippet:

<body>
    <script src="build/three.min.js"></script>
    <script>
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

    var renderer = new THREE.WebGLRenderer();
    renderer.setClearColor( 0xffffff, 1);
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    var ambient = new THREE.AmbientLight( 0x101030 );
    scene.add( ambient );
    var directionalLight = new THREE.DirectionalLight( 0xffeedd );
    directionalLight.position.set( 0, 0, 1 );
    scene.add( directionalLight );
    var loader = new THREE.ObjectLoader();
    loader.load( 'brikk2.js', function ( object ) {
        scene.add( object );
    } );
    camera.position.z = 5;
    var render = function () {
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    };
    render();
</script>
</body>

UPDATE

The initial code I presented earlier in the question was correct, but it was specifically for Geometry loading.

loader = new THREE.JSONLoader();
loader.load( 'ugeometry.json', function ( geometry ) {
mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( 'environment.jpg', new THREE.SphericalReflectionMapping() ), overdraw: 0.5 } ) );
scene.add( mesh );

So, here's the summary:

If you save as GEOMETRY from threes/editor or Clara.io, use JSONLoader. If you save as OBJECT, utilize ObjectLoader. And if you save as SCENE, there should be a SceneLoader (not yet confirmed).

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

When attempting to download a PDF file through an API using JavaScript and React JS, it is found to be empty

After downloading a PDF file from the API, I encountered an issue where the PDF appears blank. Upon testing the API endpoint, I was able to view the byte stream on the console and save it as a File successfully. However, when receiving the same response in ...

I simply aim to remove a single piece of news at a time, yet somehow I manage to delete more than intended

Do you have a PHP file containing a list of news items fetched from the database? Each news item has a delete link, which looks like this: echo '<a id="'.$result_news['id_news'].'" class="j_newsdelete" href="#">Delete</a ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

Timer for searching webpages using Javascript

I am looking for a way to continuously search a specific webpage for a certain set of characters, even as the text on the page changes. I would like the program to refresh and search every minute without having to keep the webpage open. In addition, once ...

Error: JSON requires string indices to be integers

I need help filtering JSON data from a webhook. Here is the code I am working with: headers = { 'client-id': 'my twitch client id', 'Authorization': 'my twitch oauth key', } params = ( ('query' ...

A technique for making the placeholder flash when an input textfield loses focus

I am trying to implement a blinking effect on the placeholder text when the input field loses focus. Here is the HTML code I have written: <input type="text" id="keyfob" class="customform col-sm-12 text-red" data-required='true' placeholder= ...

What is the best way to extract a generic class parameter from JSON in Scala?

Has anyone encountered a similar scenario as mine? trait Getter[A] { def get: A } I have defined two implementations of classes that implement this trait: case class CoalesceGetter[A](getters: List[Getter[String]]) extends Getter[A] { override def g ...

Utilize AngularJS ngResource to transmit JSON data to the server and receive a response

My Angular JS application requires sending data to the server: "profile":"OLTP", "security":"rsh", "availability":"4", "performance": { "TRANSACTION_PER_SEC":1000, "RESPONSE_TIME":200, "CONCURRENT_CONNECTION_COUNT":500, "STORAGE_SIZE": ...

"The challenge of achieving a transparent background with a PointMaterial texture in ThreeJS

When creating a set of particles with THREE.Points and using a THREE.PointMaterial with texture, I noticed that the transparency of the particles is working only partially. The textures are stroke rectangles created with canvas. Here is what my particles ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Filter the ng-repeat in Angular based on the model's value

Within my "Saving" model, there is a field called "Retailer". I want to implement an ng-repeat directive that displays only items with the same "Retailer" value. Essentially, I am attempting to rectify this issue. <div ng-repeat="saving in savings | ...

Remove an item from an array of objects based on its value

Within the array of nested objects provided below: [ { "items": [ { "name": "See data", "href": "/data", }, { ...

How about a demonstration of Angular and Ionic working together in a chat

I am attempting to replicate a similar example found in the default Ionic template (tabs). This example features a tab labeled chat containing multiple images with descriptions. When an item in the list is clicked, more detailed information is displayed. T ...

Is there a way to extract only the initial row of information from a Google sheet using Vue.js?

I am working on a small project that involves connecting to a Google Sheet through a basic Vuetify website. The data from the sheet is being directly pulled in to be displayed on the website, but I specifically want only the first row of data to show on th ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

Unable to convert the object to JSON format

Hey there, I've been encountering an issue while trying to register or login using my virtual device: E/StorageHelpers: Failed to turn object into JSON java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject com ...

Is there a way to identify which specific item in a watched array has been altered in VueJS?

Imagine having an array declared in the data section like this: data() { return { myData : [{foo:2, bar:3},{foo:4,bar:5}] } } If you want to identify when the bar property of the second element changes, what should your watch function look li ...

Is it possible to access an image's width and height in Jekyll Liquid syntax while iterating through a for loop, and then convert it to a JavaScript variable?

Is there a way to define a variable in Liquid logic that captures an image's width and height, which can then be passed to a JavaScript variable later on? Below are the steps my website takes before reaching the point where I need to use the image si ...

Failure to load content into element with .load function

My code looks like this: $(function () { $('#result').load('_shared.html body > :not(main)'); }); However, the <div id="result" /> element remains empty. When I try the same selector in the console on _shared.html: $(&a ...