0

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.

3 Answers 3

1

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}]'

Sign up to request clarification or add additional context in comments.

1 Comment

That is indeed a problem, but not the only one.
0

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 }; }));

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.