Generating JSON data on the fly using D3.js scripting

I am attempting to create a JSON object dynamically by pulling data from an array in D3 JavaScript. (The code below is not the exact one I used, but similar)

 let radius = [10,20,30];
   let jsonradius = '[{';
   for (let i = 0; i < radius.length; i++) {
       jsonradius += '"radius":';  
       jsonradius += 'radius[i]';
       jsonradius += ',';
   }
   jsonradius += '}]';

By using flags, I ensure that a comma is not placed after the last entry, resulting in a perfectly formatted JSON when printed using the text(jsonradius) function.

'[{"radius":10,"radius":20,"radius":30}]'

However, when I try to access it as shown below, no value is returned.

'd3.selectAll("circle").data(jsonradius).enter().select("circle").attr("r",function(d){return d.radius;});'

I am new to D3 and JavaScript. Please guide me on how to build JSON objects dynamically.

Answer №1

The JSON data you provided has 3 fields that share the same name, which is incorrect. A correct format would be similar to this:

'[{"radius":10},{"radius":20},{"radius":30}]'

Answer №2

If you're using d3, there's no need to convert your data to JSON just to access it.

You can achieve what you want directly with the radius array:

d3.selectAll("circle").data([15, 25, 35]) // Insert your array values here
  .enter()
  .append('circle')  // Make sure it's not .select('circle')
  .attr('r', function (d) { return d; })
  // add any other necessary attributes.

And if you ever need to convert strings to JSON or vice versa, you can utilize JSON.stringify:

jsonRadius = JSON.stringify(radius.map(function (r) { return { radius: r }; }));

Answer №3

It is not advisable to construct JSON through concatenation as it may lead to unexpected results. Depending on how you handle the string, it could introduce vulnerabilities in your code. Utilize the browser's JSON encoder instead...

radius = [10,20,30];
data = radius.map(function(d){return {radius: d};});
JSON.stringify(data);

This method is compatible with

  • IE8+
  • Firefox 3.1+
  • Safari 4.0.3+
  • Opera 10.5+
  • For other browsers, refer to Can I Use

If you need to cater to a browser lacking native parsing support, consider using a reliable solution for encoding to ensure proper sanitization. An example is json2.js, which can detect the absence of a native solution and provide its own if necessary.

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

Adjusting height in Google Maps to fill the remaining space

Currently, I am developing a map application where I want the Google Maps DIV to occupy the remaining height under the header. Here is the code snippet: <!DOCTYPE html> <head> <title>Map Application</title> <style type ...

Issue encountered with the DevExtreme npm module: Uncaught TypeError - $(...).dxButton is not recognized as a function

Instructions for installing DevExtreme npm can be found on their official page here: https://www.npmjs.com/package/devextreme var $ = require('jquery'); require('devextreme/ui/button'); var dialog = require('devextreme/ui/dialog&a ...

The jQuery script designed to verify the page height doesn't appear to be functioning as intended

Below is a snippet of jQuery code that I'm working with: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> hasVBar=""; hasHBar=""; $(docume ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

Difficulty updating Material UI table

Currently in the process of updating my react site to version 16.8, I have encountered an issue with a material ui table. The functionality involves users selecting certain options, triggering a rest call when a button is clicked, and then displaying the r ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Tips for ensuring that the lightbox scrolling feature only affects the lightbox and not the entire page

Currently, I am utilizing the lightbox_me jQuery plugin to trigger a lightbox when a user clicks on a product. The issue I am facing is that the lightbox content often extends below the visible area, causing the entire page to scroll when using the right s ...

The standalone package for webpack's CLI tool has been introduced as webpack-cli

Currently venturing into the world of React.js, I decided to follow the tutorials provided on tutorialspoint. However, during the implementation phase, I encountered an error message in the console upon executing the 'npm start' command: C:&bsol ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

Vuex was unable to locate the required dependency

Currently, I'm following an instructional video that incorporates Vuex. As shown in my package.json dependencies, I have installed Vuex: { "name": "blabla", "version": "1.0.0", "description": "blablaa", "author": "blabla", "private": true, ...

The lack of functionality for lockOrientation in Cordova is causing issues

Currently working with Cordova, I am attempting to set the screen orientation to landscape for Android. Utilizing the screen-orientation plugin found at: https://www.npmjs.com/package/cordova-plugin-screen-orientation In my JavaScript code, I have impleme ...

ReactJS integration issue with Material Design Lite (import/require problem)

I am currently integrating Google's Material Design Lite with ReactJS. Specifically, I am utilizing the Spinner Loading and Text Field components from the MDL library. However, I am encountering an issue when switching routes using React Router. The ...

Create a hash by converting arrays into a single array using Ruby mapping

In my programming project, I have an array called dates with 31 items (shown in a shortened form below) Tuesday 8, November Wednesday 9, November #etc. Also, there is a hash named movies with 31 entries, each containing movie names and showtimes (abbrevi ...

Exploring the Versatility of Axios

Today, I implemented an AJAX request using Axios in JavaScript to submit form data. While the requests are being sent successfully, it seems that the backend is not able to receive the username and password information from the frontend. What could be ca ...

Error: You forgot to close the parenthesis after the argument list / there are duplicate items

I have already tried to review a similar question asked before by checking out this post, but unfortunately, I still couldn't find a solution for my problem. Even after attempting to add a backslash (\) before the quotation mark ("), specificall ...

Steps to Retrieve and Showcase a Compilation of YouTube Clips with JavaScript

Recently, I managed to write a C code that retrieves the list of YouTube videos from the URL "*http://gdata.youtube.com/feeds/api/standardfeeds/top_rated*" using the libsoup library. By utilizing libxml2, I was able to parse the XML data and extract specif ...

Subdomain redirection issue with express-subdomain for localhost GET requests

In order to manage requests to specific subdomains, I am utilizing a package in express.js called express-subdomain. From my understanding, the subdomain constructor function requires an express router object that I pass from an exported router module. M ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

How to access a specific element within an ng-grid

My grid options include: $scope.ngOptions = { data: 'data', columnDefs: [ {field: 'Status', displayName: "Status", cellTemplate: selectTableTemplate, enableCellEdit: true}, {cellTemplate: &apos ...

Sending JSON data through an HTTP POST request using Arduino

I am attempting to send JSON data using an Arduino. When running this code, I attempt to send the JSON data with a QueryString parameter. However, when I try this code, the server responds with a message stating that the QueryString format is incorrect, in ...