JSON.parse:JSON数据之后的意外非空白字符

时间:2012-04-21 10:46:41

标签: javascript jquery json

我希望创建一个JSON对象,该对象派生自4个选择菜单的选定选项。这些菜单可能在加载时选择了选项(由于服务器端技术),或者可能没有选择任何选项!一旦使用$(document).ready()加载页面,我的脚本就会运行......但是我遇到了一些JSON对象的问题“ JSON.parse:JSON数据后出现意外的非空格字符

我希望我的JSON具有以下结构

selObj = {

    category: selectedCategory, // we can only have 1 category, this isn’t giving me a problem…

    catOptions:{
        optionValue:discountValue, // we can have many of these
        optionValue:discountValue,
        optionValue:discountValue
    },

    tariff:{
        tariffValue:discountValue, // we can have many of these
        tariffValue:discountValue
    },

    tarOptions:{
        tarOption:discountValue, // we can have many of these

    }

};

好的,这是我的函数,我已经删除了一些项目以简化,但我将一个原始的空对象作为参数传递给函数,然后希望修改它,因为我想要将JSON对象传递回服务器if /何时更改选择菜单...但是现在我们只处理页面加载...该函数还显示了使用名为defaultTable()的函数创建的动态表中的值或选择内容暂时忽略它,它是我感兴趣的JSON对象的填充(并且有问题)。

var selectMenuArray = ["cat", "catOpt", "tariff", "tariffOpt"], // these are the IDs of the select menus...     
selObj = {};

function setUpTable(selectArray, theObj){

    // okay, if we enter the page and and the user already has a tarif selected (so it is shown in the menus) we wish to show the table with the 
    // default/original values...

    var currentSelect,
        catA = [],
        catOptA = [],
        tarA = [],
        tarOptA  = [],
        catOptForObj,
        tariffForObj,
        tariffOptForObj,
        temp1 = {},
        temp2 = {},
        temp3 = {},
        i;

    // loop through the 4 menus and see what is selected
    for(i=0;i<selectArray.length;i++){
    // let's look at the options to see if any are selected by looping through the <option>
        currentSelect = document.getElementById(selectArray[i]);

        for(j=0;j<currentSelect.length;j++){
            // do we have an options with the selected attribute?
            if(currentSelect.options[j].selected == true){
                // okay, we need to make sure the table is shown then the correct values are shown?
                // we know what the Menu is... selectArray[i], and this is the text... currentSelect.options[j].
                // lets build up whet's selected in Arrays...
                switch(selectArray[i]){
                    case "cat":
                        catA.push(currentSelect.options[j].value);
                        break;
                    case "catOpt":          
                        catOptA.push(currentSelect.options[j].value);
                        catOptForObj = catOptForObj + '"' + currentSelect.options[j].value + '":"' + "% to come later" + '",';
                        break;
                    case "tariff":
                        tarA.push(currentSelect.options[j].value);
                        tariffForObj = tariffForObj + '"' + currentSelect.options[j].value + '":"' + "% to come later" + '",';
                        break;  
                    case "tariffOpt":
                        tarOptA.push(currentSelect.options[j].value);
                        tariffOptForObj = tariffOptForObj + '"' + currentSelect.options[j].value + '":"' + "% to come later" + '",';
                        break;  
                    default:
                    // no default?
                }
            }
        }
    }

    // now we can build the table
    if(catA.length > 0 || catOptA.length > 0 || tarA.length > 0 || tarOptA.length > 0){

        // show table...
        $("#dynamicTableHolder table").css("visibility","visible").hide().fadeIn('slow');

        for(i=0;i<selectArray.length;i++){  
            switch(selectArray[i]){ 
                case "cat":
                    defaultTable(catA, "dtCats");
                    theObj.cat = catA[0];
                    break;
                case "catOpt":          
                    defaultTable(catOptA, "dtTariffs");
                    temp1 = '"{' + catOptForObj.substring(0, catOptForObj.length-1).replace(/undefined/g, "")  + '}"'; 
                    theObj = jQuery.parseJSON('"catOptions":' + temp1);
                    break;
                case "tariff":
                    defaultTable(tarA, "dtCatOpts");
                    temp2 = "{" + tariffForObj.substring(0, tariffForObj.length-1).replace(/undefined/g, "") + "}";
                    //theObj = jQuery.parseJSON('"tariff":' + temp2);
                    break;  
                case "tariffOpt":
                    defaultTable(tarOptA, "dtTariffOpts");
                    temp3 = "{" + tariffOptForObj.substring(0, tariffOptForObj.length-1).replace(/undefined/g, "") + "}";
                    //theObj = jQuery.parseJSON('"tarOptions":' + temp3);
                    break;  
                default:
                // no default?
            }
        }
    }

}

我在制作JSON对象时遇到问题,我正在尝试做的是在循环时连接字符串,然后使用jQuery.parseJSON方法将这些字符串转换为对象...但是我没有正确地执行此操作。我甚至尝试在创建temp1时更改引号。

我知道这很复杂,我可能会问很多,但任何人都可以看到我做错了什么。我对jQuery.parseJSON并不熟悉所以任何建议都会很棒,因为我觉得我疯了!

如果我模糊不清或者自己解释不好请说出来......我也把它放在小提琴上...... http://jsfiddle.net/itakesmack/JSRt7/1/

请注意,这是一个工作进展,因此有些项目可能会丢失或需要开发(或者我可能有其他错误......但我希望不会这样做。)

2 个答案:

答案 0 :(得分:3)

你正在为parseJSON()提供一个看起来像'"catOptions":"{"A":"B","C":"D",}"'的字符串 parseJSON()需要看起来像这个 '{"catOptions":{"A":"B","C":"D"}}'

的东西

如果你要手工构建JSON,你会遇到一些问题。

要解决您的错误,您不希望将{key:value}包装在引号中,它们会被catOptForObj中的引号打破

如果它们可能包含双引号,您需要转义构建OptForObj字符串的值

你基本上是这样建立你的字符串:

s = s + '"' + A '":"' + "B" + '",';

会产生类似"A":"B","C":"D",

的内容

逗号应仅存在于值之间。一种方法是先检查s是否为空,然后在附加值之前将其附加到s。类似的东西:

s = (s.length?(s+','):'') + '"' + A + '":"' + "B" + '"';

最好的方法是依赖评论中建议的JSON.stringify等内置函数

答案 1 :(得分:0)

要向正在使用字符串的JSON对象添加值。

catOptForObj = catOptForObj + '"' + currentSelect.options[j].value + '":"' + "% to come later" + '",'; 

相反,您可以尝试以下约定将值分配给JSON中的不同键。

catOptForObj[currentSelect.options[j].value] = "% to come later";