bukli
bukli

Reputation: 172

Building JSON dynamically in D3 javascript

I am trying to build a JSON dynamically by reading from an array in D3-javascript. (The below code is not the actual one I used, but similar to this)

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

using flags I make sure that the comma is not placed after the last entry and it comes out as a perfect JSON when I print using text(jsonradius) function. '[{"radius":10,"radius":20,"radius":30}]'

But when I try to access it like as follows, 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. Pls help how to build json dynamically.

Upvotes: 0

Views: 358

Answers (3)

Christopher Hackett
Christopher Hackett

Reputation: 6192

You should not really attempt to build the JSON by concatenation as this could easily result in something unexpected happen. Depending what you later do with the string it could be a vector to attach whatever you are building. Use the browsers JSON encoder ...

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

This will work in

  • IE8+
  • Firefox 3.1+
  • Safari 4.0.3+
  • Opera 10.5+
  • Check other browsers at Can I Use

If you need to support a browser which does not have built in parsing support then consider using a well tested solution to do the encoding so that the correct sanitation is preformed. A good example is json2.js which detects if there is no native solution and 'polyfils' its own solution if needed.

Upvotes: 0

musically_ut
musically_ut

Reputation: 34288

You do not need to convert the data to JSON to be able to access it via d3.

What you want can be done using the radius array itself:

d3.selectAll("circle").data([10, 20, 30]) // Use your array here
  .enter()
  .append('circle')  // not .select('circle')
  .attr('r', function (d) { return d; })
  // other properties.

And, for sake of completeness, you can use JSON.strinfigy to convert strings to and from JSON:

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

Upvotes: 0

Zergatul
Zergatul

Reputation: 2010

Your JSON object contains 3 fields with the same name. It is an error. It must be something like this: '[{"radius":10},{"radius":20},{"radius":30}]'

Upvotes: 1

Related Questions