gpt4 book ai didi

javascript - 使用 jquery 将 obj 格式化为 json

转载 作者:行者123 更新时间:2023-11-28 19:14:44 25 4
gpt4 key购买 nike

我正在使用jqCloud插件来生成词云。该脚本依赖于以特定模式格式化的 json。我正在尝试将 var msg 解析为 json,就像在 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);

最佳答案

您手动创建的字符串对于尝试满足您的输出需求没有任何好处。

您正在寻找的数据结构是一个对象数组。这张 map 应该可以满足您的需求

var word_array= $.wordStats.topWords.map(function(item, index){
return { text: item.substring(1) , weight: $.wordStats.topWeights[index] };
});

$('#example').jQCloud(word_array);

提示:永远不要尝试手动创建 JSON...它很容易出错。创建数组和/或对象,如果您确实需要将其作为 JSON 转换整个结构。在这种情况下,您需要一个实际的数组...而不是 JSON

关于javascript - 使用 jquery 将 obj 格式化为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30114023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com