【问题标题】:obj formatted to json using jqueryobj 使用 jquery 格式化为 json
【发布时间】:2015-05-08 00:48:27
【问题描述】:

我正在使用 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);

【问题讨论】:

    标签: javascript jquery json parsing


    【解决方案1】:

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

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

    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

    【讨论】:

    • 感谢有关手动创建 json 的提示,很高兴知道!!我尝试了您的 sn-p 并在控制台中收到此错误。 Uncaught TypeError: Cannot read property 'map' of null
    • 你把它放在for 循环所在的位置和clear() 之前。知道错误来自哪一行以及什么文件也很重要。可能是下一个插件或此代码或??
    【解决方案2】:

    您可以构造一个对象并在之后将其字符串化,尽管您可能不需要并且可以直接将对象提供给 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);
    

    【讨论】:

    • 谢谢,这让我更接近了,但我现在收到错误 Uncaught TypeError: Cannot assign to read only property 'weight' of [ 似乎无法钻入数组并将左括号解释为第一个对象。
    • 将对象提供给jqcloud时发生错误?
    • 根据 charlietfl 的评论,我将 $.wordStats.clear(); 移到了底部,现在它可以工作了。谢谢大家!!我赞成 charlietfl cmets 但选择这个答案是为了避免手动创建 json。
    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 2011-06-30
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多