2012-04-21 10 views
8

Deseo crear un objeto JSON que se derive de las opciones seleccionadas de 4 menús de selección. ¡Estos menús pueden tener opciones seleccionadas cuando se cargan (debido a una tecnología del lado del servidor) o pueden no tener opciones seleccionadas de ningún modo! Una vez que la página se carga utilizando $ (document) ready() mi escritura funciona ... sin embargo yo estoy haciendo algunos problemas con el objeto JSON “JSON.parse: no está en blanco inesperado después de JSON datosJSON.parse: carácter no blanco inesperado después de datos JSON

I quiero que mi JSON a tener la siguiente estructura

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 

    } 

}; 

Bueno aquí está mi función, he eliminado algunos elementos aquí para simplificar, pero estoy pasando un objeto vacío original en la función como un argumento y luego con la esperanza de modificar esto como si quisiera pasar el objeto JSON de regreso al servidor si/cuando se cambian los menús de selección ... pero por ahora solo estamos lidiando con la carga de la página ... la función también muestra th e valores o lo que se selecciona en una tabla dinámica que se crea utilizando una función llamada defaultTable(), simplemente ignore que, por el momento, es la población del objeto JSON que me interesa (y tengo problemas con).

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? 
      } 
     } 
    } 

} 

estoy teniendo problemas con la fabricación del objeto JSON, lo que estoy tratando de hacer es concatenar cadenas, mientras que bucle, entonces éstos encubierta a objetos utilizando el método jQuery.parseJSON ... sin embargo yo no estoy haciendo esto correctamente. Incluso he intentado cambiar las comillas al crear temp1.

Sé que esto es complicado y que puedo estar preguntando mucho pero ¿alguien puede ver lo que estoy haciendo mal? No estoy tan familiarizado con jQuery.parseJSON así que cualquier consejo sería genial ya que creo que me estoy volviendo loco.

si estoy siendo vaga o no explicar a mí mismo así decirlo favor ... También me he puesto esto en el violín ... http://jsfiddle.net/itakesmack/JSRt7/1/

Recuerda: Este es un proceso de trabajo así que algunos artículos pueden faltar O NECESITA SER DESARROLLADO (o puedo tener otros errores ... pero espero que no).

+13

NUNCA construir JSON usando funciones de cadena. Use 'JSON.stringify()' en un objeto apropiado. – ThiefMaster

+0

Eso es un gran consejo ... Voy a dar una oportunidad, gracias! –

+1

Recuerde también no agregar comentarios reales en su JSON como si fuera JavaScript; JSON no los permite (a menos que los incluya como parte del objeto) –

Respuesta

3

Usted está alimentando parseJSON() una cadena que parece '"catOptions":"{"A":"B","C":"D",}"' parseJSON() quiere algo que se parece a este '{"catOptions":{"A":"B","C":"D"}}'

Tienes algunos problemas para hacer frente a si se va a construir el JSON a mano.

para arreglar sus errores no desea envolver su {key:value} entre comillas, que están siendo rotos por las cotizaciones dentro catOptForObj

Tendrá que escapar de los valores que están construyendo cadenas OptForObj con si ellos pueden contener comillas dobles

Usted es básicamente la construcción de su cadena como esta:

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

que producirá algo así como "A":"B","C":"D",

Las comas solo deberían existir entre valores. Una forma de hacerlo es verificar si s está vacío primero y solo añádalo a s antes de su valor adicional. Algo como:

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

Lo que sería mejor es confiar en una función incorporada como JSON.stringify como se sugiere en los comentarios

0

Para agregar valores a un objeto JSON, está utilizando una cadena.

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

En su lugar, puede probar la siguiente convención para asignar valores a las diferentes claves en JSON.

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

Cuestiones relacionadas