سؤال

When trying to use a JSON.stringify() method to turn an array of strings into a JSON object that I can pass through to a PHP script, the stringify() method fails to return anything of significance.

This is the only code that the input is being passed through. It is not being tampered with by anything else.

function submitItem() {
 try {
    var item = [];
    item.name = $('.itemText').val();
    item.type = $('.itemType').val();
    item.price = $('.itemPrice').val();
    item.color = $('.itemColor').val();
    item.desc = $('.itemDesc').val();
    item.image = $('.itemImage').val();
    item.giftType = $('.itemGiftType').val();
    item.avail = $('.itemAvail').val();
    item.giftable = $('.itemGiftable').val();
    item.ranking = $('.itemRanking').val();
    item.basicTrack = $('.itemBasic').val();
    item.vetTrack = $('.itemVet').val();
    item.month = $('.itemMonth').is(':checked');
    item.hidden = $('.itemHidden').is(':checked');
    item.id = $('.itemID').val();

     //Left in for confirmation purposes
    var join = [];
    join[0] = 'test';
    join[1] = 'tset';
    console.log( JSON.stringify( join ) );

    console.log(item);
    var JsonItem = JSON.stringify(item);
    console.log( JsonItem );
 } catch (err) {
    console.log(err.message);
 }
}

This produces the following output in the console:

The output corresponds to the three console.log() lines at the bottom of the script

As you can see, the log for both JSON items returns as [] rather than any JSON string of any sort.

Any potential reason that this would occur would be appreciated.

Thanks.

هل كانت مفيدة؟

المحلول

You're initializing your "item" as an array. You should be initializing it as a plain object ({}):

var item = {};

When the JSON serializer sees an actual array, it only operates on the numerically-indexed properties.

نصائح أخرى

You should convert join to object before stringify

console.log( JSON.stringify( {arr: join}) );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top