How to Fetch JSON in Babylon.js

Hi everyone could you help me. How do I use a standard fetch() request to retrieve a JSON file that i can then map through to return an array. I am using the returned array to draw a line/graph. I have tried using fetch in the standard way and i have also tried using the following code from chat GPT but with no luck. Thanks in advance John

BABYLON.SceneLoader.ImportMeshAsync(“https://jsonplaceholder.typicode.com/users”, “”, “”, scene, function (meshes, particleSystems, skeletons) {
// JSON data is fetched, you can access it through the “meshes” variable
const jsonData = meshes[0];
const users = jsonData.map(user => {
// Use map to transform the data as needed
return {
id: user.id
};
});
});

var jc = users
var myPoints1 = [];

for(var i = 0; i<jc.length; i++){
myPoints1.push(new BABYLON.Vector3(1, jc[i], -8))

}

var lines = BABYLON.MeshBuilder.CreateTube("lines", {path: myPoints1, radius: 0.2, sideOrientation: BABYLON.Mesh.DOUBLESIDE}, scene)
lines.material = mat3;

Use the standard fetch method(const response = await fetch(‘htps://linktoyourjsonfile.com/file.json’)) and turn the response to JSON i.e const jsonData = await response.json();
Map it and return the data(like you did there and voila, you’re done).

Reasons using the standard way won’t work… Maybe a CORS error. check the console for errors.

3 Likes

thanks for this…i worked out that standard fetch() works, turns out the problem i was having was that the async fetch wasnt returning in time for a synchronous process that needed to use the fetched data. Solved it by putting the synchronous process inside the async fetch function… thanks again for your help

1 Like