Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine.

The following JSON source doesn't seem to work:

function reformat(data) {

var jsonObject = JSON.parse(data, function(k, v) {
    return (typeof v === "object" || isNaN(v)) ? v : parseInt(v, 10);
});

var treeData = (JSON.stringify(makeTree(jsonObject), null, 4));
//etc code for D3 
}

However, if I log the data to the console and define it as follows:

treeData = [
    {
        "id": 1,
        "name": "Start",
        "children": [
            {
                "id": 2,
                "name": "Decision A",
                "children": [
                    {
                        "id": 4,
                        "name": "Possibility A-1",
                        "children": [
                            {
                                "id": 8,
                                "name": "Consequence A-1"
                            }
                        ]
                    },
                    {
                        "id": 5,
                        "name": "Possibility A-2",
                        "children": [
                            {
                                "id": 9,
                                "name": "Consequence A-2"
                            }
                        ]
                    }
                ]
            },
            {
                "id": 3,
                "name": "Decision B",
                "children": [
                    {
                        "id": 6,
                        "name": "Possibility B-1",
                        "children": [
                            {
                                "id": 10,
                                "name": "Consequence B-1"
                            }
                        ]
                    },
                    {
                        "id": 7,
                        "name": "Possibility B-2",
                        "children": [
                            {
                                "id": 11,
                                "name": "Consequence B-2"
                            }
                        ]
                    }
                ]
            }
        ]
    }
];

It suddenly works without any issues. It's quite frustrating to have to keep copying and re-declaring the variable. If the outputs are identical, why does it behave this way?

The function is triggered once the web page loads:

 function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); 
    oReq.onload = function() {

       reformat(this.responseText);
    };
    oReq.open("get", "getData.php", true);

    oReq.send();

Answer №1

What is the purpose of converting the JSON string and then passing it to treeData?

Try this alternative approach

var treeData = makeTree(jsonObject);

Give it a shot and see if it helps.

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

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...

The asp.net code behind is reporting an undefined response text

var xhr = $.ajax({ type: 'GET', cache: false, url: 'loc.aspx?count=' + str, dataType: 'json', contentType: "application/json; charset=utf-8", async: false ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

What is the best way to dismiss the modal window in React upon clicking the "Add product" button?

Hello all, I'm having trouble figuring out how to close the modal window in React. I want it so that when the user clicks on the "Add" button, a modal window opens for data input, and then upon clicking the "Add product" button, the window closes imme ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...

JSON is often portrayed as a singular value

I am attempting to save settings in my SQL Database and then restore them using ajax and php. However, I am encountering an issue where only one long JSON Value is returned instead of three separate values for each setting. Settings: {"setting1":"true","se ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

I'm puzzled as to why my Vuex modules are not functioning properly. I keep receiving the error message: "[vuex]

I've been searching for hours and can't figure out why I keep getting this error message: [vuex] unknown mutation type: groceryStore/getStoreApple on all of the commits to the mutations in the groceryStore-module. I believe I'm following the ...

How to extract an inner array from a serialized string-array

Currently, I am in the process of developing a REST-API and to populate my database, I am utilizing large JSON files containing existing data. However, I have encountered an issue with deserializing one of the fields. The structure of the JSON file is as ...

Using Laravel 8 to create connected dropdown menus with the power of Ajax

Struggling with setting up a dependent dropdown menu in Laravel 8 using Ajax. The first dropdown works fine, but the next two don't display any options. Being new to Laravel, I'm having trouble pinpointing the problem areas. Seeking assistance to ...

What steps can I take to condense and tidy up this output into a more compact string?

Recently, I've been experimenting with Google's APIs and attempting to create a terminal command that can inform me of the distance and travel time to a particular location. However, I'm running into an issue with the current output format: ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

Deciphering JSON to UTF-8StringEncoding

I need help decoding JSON output to UTF-8. $sql = "select * from nganhang"; $kq = mysql_query($sql); $posts = array(); while($post = mysql_fetch_assoc($kq)) { $posts[] = array('node_list_bank'=>array_map('utf8_encode&ap ...

Is it considered acceptable to perform roughly 100 queries on the Android SQLite database for the purpose of storing a single data item?

I have recently incorporated SQLite data storage into my Android translator app. The current situation is as follows: the app receives translations in JSON format from a server, then proceeds to parse it and build an object tree consisting of 50 to 100 obj ...

Updating database with Ajax when the button is clicked

Seeking guidance with a project as I am still grasping the concepts of javascript and jquery. The goal is to update a database entry upon clicking a button, where the content of the button is fetched from the database. Initial step involves querying the d ...

Dividing internal CRUD/admin panel from the live application

Currently developing a moderately complex react app with redux. We have a production version that meets our requirements and now we are working on an administrative area for a local version of the application. This local version will only have basic CRUD f ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

Exploring the ins and outs of webpage loading speed

I am working on writing JavaScript code that includes a button to open a webpage of my choice. I now want to understand how to detect when the page I called is finished loading. Any suggestions or ideas on this topic? I apologize if my explanation was no ...