Using JSON to store the image URLs instead of encoding them in base64

I am currently utilizing Three.js to store and retrieve objects in a database. The objects are being inserted as JSON format.

However, the issue I am facing is that when using JSON.stringify or toJSON(), it converts the image url (textures) into base64 format instead of retaining the http URL.

Here is the original JSON data:

{
    "metadata": {
        [...]
    },
    "geometries": [
        {
            [...]
        }],
    "materials": [
        {
            [...]
        }],
    "textures": [
        {
            [...]
        }],
    "images": [
        {
            "uuid": "4ED9CE3E-7C8A-4EB7-8CF8-D90B3527DF5F",
            "url": "data:image/png;base64,iVBORw0KGgoATyuRZGZVREd0FAERRRBAEBEFwAYEyKqP/Rfozx+5fDYjvpeT/akv+n/J+/7eMjX9Ke8uojP4JVAYAyuj/Ld3Por7fPQ9i8d7vvr8LKNzLg/dn1u1hvQf3q/v92vRX0X/ [...]"
        }],
    "object": {
        [...]
    }
}

The desired output for JSON would be:

{
    "metadata": {
        [...]
    },
    "geometries": [
        {
            [...]
        }],
    "materials": [
        {
            [...]
        }],
    "textures": [
        {
            [...]
        }],
    "images": [
        {
            "uuid": "4ED9CE3E-7C8A-4EB7-8CF8-D90B3527DF5F",
            "url": "http://www.domain.com/picture/path.png"
        }],
    "object": {
        [...]
    }
}

Is there a solution available to achieve this?

Answer №1

Dealing with a similar issue, I found a solution by redefining Source.toJSON() in the following way:

Source.prototype.toJSON = function ( customData ) {

    const isMainObject = ( customData === undefined || typeof customData === 'string' );

    if ( !isMainObject && customData.images[ this.uuid ] !== undefined ) {
        return customData.images[ this.uuid ];
    }

    const result = {
        uuid: this.uuid,
        url: this.data.src
    };

    if ( !isMainObject ) {
        customData.images[ this.uuid ] = result;
    }

    return result;
}

Another option is to save the relative image URL using this.data.getAttribute('src').

Answer №2

Upon analyzing the JSON file and obtaining the texture path, I executed the following steps:

let parsedObject = SELECTED.toJSON(); // convert selected object to JSON
base64Texture = parsedObject.images[0].url; // retrieve base64 encoded image value
parsedObject.images[0].url = texMap; // replace base64 encoded image with http texture path

parsedObject = JSON.stringify(parsedObject, null, '\t' );
parsedObject = parsedObject.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1'); // format the JSON for readability

And voila, the solution worked perfectly! :)

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

What is the best way to show a tooltip alongside highlighted text?

How can I display a tooltip (using qTip) next to selected text? The code below captures the selected text in the console, but the tooltip is not displayed. <div class='test'>Actual text will be much longer...Test Test Test Test Test Test T ...

The Final Div Fluttering in the Midst of a jQuery Hover Effect

Check out my code snippet here: http://jsfiddle.net/ZspZT/ The issue I'm facing is that the fourth div block in my example is flickering quite noticeably, especially when hovering over it. The problem also occurs occasionally with the other divs. Ap ...

Automatically input the city once the zip code has been entered

Trying to automatically fill in the CITY: field when entering the zip code results in an "undefined variable: array on line.." error where value="< ? php $array['navn'] "> Is there anyone who can provide assistance with this issue? View ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Is there a way to store a complete array within a single cell?

I am searching for a solution to assign an entire array to a cell in Google Apps Script and Google Sheets. My attempt at using cell.setValue(array) only resulted in the cell containing the first item of the array. var cell = SpreadsheetApp.getActiveSprea ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Why isn't my output being shown on the screen?

Why is the output (refresh value) not being displayed? function myFunction() { $a = document.getElementById("examplehtml").value; document.write("<big><bold>"); document.write($a); document.write("</bold></big>"); $b = ...

Creating a jQuery countdown script

Is it possible to easily convert the function below into jQuery and still maintain the ability to call multiple instances of the countdown? This particular function receives a server time echoed by the server and then initiates a countdown to the specifie ...

When displaying JSON data in a Xamarin Forms listview, the items may not appear in the desired order as specified in the

Dealing with a JSON database that is loaded into a listview has presented a challenge for me. The JSON data I receive is already ordered the way I want it, but when it is grouped into different categories, it does not maintain its order in the listview. T ...

Mudblazor - Tap or click within the designated area to trigger the drag and drop functionality

I have incorporated the Mudblazor CSS framework into my Blazor WebAssembly project. Within the drag and drop zone, I have included a button that is supposed to remove each uploaded image. However, when I click on the remove button, it only opens up the fi ...

Exploring the dynamic duo of Github and vue.js

As I am new to programming and currently learning JavaScript and Vue.js, I have been trying to deploy my first Vue.js app without success. Despite spending hours on it, I still cannot figure it out and need to seek assistance. Every time I try to deploy, ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Utilizing jq for tallying

When using jq-1.5 and given a JSON file like: [{... ,"sapm_score":40.776, ...} {..., "spam_score":17.376, ...} ...] Is there a way to determine the count of items where sapm_score > 40? - Regards, Dan Update: Upon examining the input file, it appea ...

Guide on transferring a JSON to an ASP.NET API Controller from an Android Studio application

Creating a new app has been an exciting project for me. The app requires users to input various information such as their name and age into text fields. Once the user clicks a button, the data is sent to my API controller where the put method saves it in a ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

The JSON request has either timed out or produced an inconsistent result

Utilizing JSON and YQL to gather data from an external domain has presented me with a challenge. http://example.com/NdkPU/22/ The issue at hand is the inconsistent functioning of the code - there are times when I receive a response, while other times not ...

Obtain picture from firebase utilizing react Js

I have attempted multiple methods to download images from Firebase, but the download URL is not functioning as expected. Instead of downloading the image directly, it opens in a new tab. The function used in Firebase: export async function addMedia(locati ...