Reputation: 1779
I am using jqCloud plugin to generate word clouds. This script relies on the json to be formatted in a particular pattern. I am trying to get var msg
parsed out as json like it is in the var word_array
$(function() {
var count = 3;
$.wordStats.computeTopWords(count, $('body'));
var msg = 'Top words:\n';
for (var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
msg += '\n' + $.wordStats.topWords[i].substring(1) + ': ' + $.wordStats.topWeights[i];
}
console.log(msg);
//this is what gets printed in the console
//Top words:
//bag: 46
//tote: 30
//ugh: 30
$.wordStats.clear();
// I am trying to get var msg to spit out json
// that is formatted like this
var word_array = [{
text: "Lorem",
weight: 15
}, {
text: "Ipsum",
weight: 9,
link: "http://jquery.com/"
}, {
text: "Dolor",
weight: 6,
html: {
title: "I can haz any html attribute"
}
}
// ...as many words as you want
];
$('#example').jQCloud(word_array);
Upvotes: 0
Views: 223
Reputation: 171669
You are manually creating strings that provide no benefit toward trying to meet your output needs.
The data structure you are looking for is an array of objects. This map should give you what you need
var word_array= $.wordStats.topWords.map(function(item, index){
return { text: item.substring(1) , weight: $.wordStats.topWeights[index] };
});
$('#example').jQCloud(word_array);
Hint: never try to manually create JSON...it is highly error prone. Create arrays and/or objects and if you really need that as JSON convert th whole structure. In this case you need an actual array ...not JSON
Upvotes: 2
Reputation: 1711
You can construct an object and stringify it afterward although you maybe dont need to and can just feed the object straight away to jQCloud.
var json_obj = [];
for (var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
var w = {};
w.text = $.wordStats.topWords[i].substring(1);
w.weight = $.wordStats.topWeights[i];
json_obj.push(w);
}
var msg = JSON.stringify(json_obj);
Upvotes: 1