javascript JSON.parse:JSON 数据后出现意外的非空白字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10258230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:12:16  来源:igfitidea点击:

JSON.parse: unexpected non-whitespace character after JSON data

javascriptjqueryjson

提问by Mike Sav

I wish to create a JSON object that is derived from the selected options of 4 select menus. These menus may have options selected when loaded (due to a server side technology) or may have no options selected whatsoever! Once the page is loaded using $(document).ready() my script runs… however I'm getting some problems with the JSON object “JSON.parse: unexpected non-whitespace character after JSON data

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

I want my JSON to have the following structure

我希望我的 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

    }

};

Okay here's my function, I've removed some items here to simplify, but I'm passing an original empty object into the function as an argument and then hoping to amend this as I will want to pass the JSON object back to the server if/when the select menus are changed… but for now we're just dealing with the page loading… the function also shows the values or what is selected in a dynamic table that is created using a function called defaultTable()just ignore that for now, it's the populating of the JSON object I'm interested in (and having problems with).

好的,这是我的函数,我在这里删除了一些项目以简化,但是我将原始空对象作为参数传递给函数,然后希望修改它,因为我希望将 JSON 对象传递回服务器,如果/when the select menus are changed… but for now we're just dealing with the page loading… the function also shows the values or what is selected in a dynamic table that is created using a function called defaultTable()just ignore that for now, it's the填充我感兴趣的 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?
            }
        }
    }

}

I'm having problems with making the JSON object, what I'm trying to do is concatenate strings whilst looping, then covert these to objects using the jQuery.parseJSON method… however I'm not doing this correctly. I've even tried changing the quotation marks when creating temp1.

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

I know this is complicated and I may be asking a lot but can anyone see what I'm doing wrong. I'm not that familiar with jQuery.parseJSON so any advice would be great as I think I'm going mad!

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

If I'm being vague or not explaining myself well please say so... I've also put this on fiddle... http://jsfiddle.net/itakesmack/JSRt7/1/

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

PLEASE NOTE THIS IS A WORKING PROGRESS SO SOME ITEMS MAY BE MISSING OR NEED TO BE DEVELOPED (or I may have other bugs... but I hope not).

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

回答by Pete

You're feeding parseJSON() a string that looks like '"catOptions":"{"A":"B","C":"D",}"'parseJSON() wants something that looks like this '{"catOptions":{"A":"B","C":"D"}}'

您正在向 parseJSON() 提供一个看起来像 parseJSON() 的字符串'"catOptions":"{"A":"B","C":"D",}"'想要的东西看起来像这样'{"catOptions":{"A":"B","C":"D"}}'

You've got a few problems to deal with if you are going to build the JSON by hand.

如果您要手动构建 JSON,则需要处理一些问题。

To fix your error you don't want to wrap your {key:value}in quotes, they are being broken by the quotes inside catOptForObj

为了解决您不想{key:value}用引号括起来的错误,它们被 catOptForObj 中的引号破坏了

You'll need to escape values you are building OptForObj strings with if they may contain double quotes

如果您正在构建 OptForObj 字符串的值可能包含双引号,则需要对其进行转义

You are basically building your string like this:

您基本上是这样构建字符串的:

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

which will produce something like "A":"B","C":"D",

这会产生类似的东西 "A":"B","C":"D",

Commas should only exists between values. One way to do this is check to see if s is empty first, and only append it to s before your additional value. Something like:

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

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

What would be best is to rely on a built in function like JSON.stringify as suggested in the comments

最好是依赖内置函数,如评论中建议的 JSON.stringify

回答by Sam

To add values to a JSON object you are using string.

要将值添加到 JSON 对象,您正在使用字符串。

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

Instead you can try the following convention to assign values to the different keys in JSON.

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

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

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