I have a string variable which I have defined as:
var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],";
I am also using some javascript code which takes values in an array and draws a line graph out of those values.Part of the code is as shown below.
var graphData = [{
data: [[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],],
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
I am trying to replace the data in the array with the variable I defined above but the graph is not working when I do so. This is my code:
var graphData = [{
data: [regn],
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
Where I am going wrong or how am I supposed to get the data in my string to that array?
4 Answers 4
You need to parse the string first. This is usually done using JSON.parse :
var regn="[[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67]]";
var arr = JSON.parse(regn) // now it's an Array
If you need to support browsers that don't support JSON.parse you can patch this using JSON3
Aside: In addition to that please notice that regn has a stray trailing comma and needs to be wrapped in a [] or {} (the object approach would also need keys then, so the array is the way to go here), so it's not valid JSON the way you have posted it (don't know if this happened by accident or not).
6 Comments
[] to be valid JSON.{...} or [...] through jsonlint.com. Try "foo".{} suggestion in your edit doesn't make much sense in the context of the current example {[1,75],[2,59]} isn't valid either.JSON.parse('"foo"') with json2.js and json_parse('"foo"') with json_parse_state.js, the implementations by the author of the spec, throw no SyntaxErrors. Peculiar. :)Alternative version with regexp parsing:
var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],";
var rez = [];
var regex = /\[(\d+),(\d+)\]/g;
var match;
while ((match = regex.exec(regn)) != null) {
rez.push([match[1], match[2]]);
}
graphData.data = rez;
Comments
In place of
var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],"
try this,
var regn=[[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67]];
var graphData = [{
data: regn,
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
Comments
- Split regn by '],['.
- Strip anything but digits and commas from each chunk
- Split each chunk by ',' limited to 2 chunks
- Done!
var parseRegn = function (regnStr) {
var pairs = regnStr.split('],['), // 1
pairStr = '';
for (var i = 0; i < pairs.length; i++) {
pairStr = pairs[i].replace(/[^\d|,]/g, ''); // 2
if (pairStr.length > 0) {
pairs[i] = pairStr.split(',', 2); // 3
}
}
return pairs; // 4
};
datareceives an array of arrays and in the second instance just a string - that's, where you are going wrong. Parse your string, before passing it and you'll be fine.