2016-02-04 44 views
1

所以我想爲我的web應用做一些前端單元測試。在用戶可以添加一個產品的看法,我有以下代碼:JSON.parse返回[Object object]尋找訪問對象的屬性

var ProductEntry = {Title: ProductTitle, Description: Description, Hashtags: Hashtags, 
      Picture1: Picture1, Picture2: Picture2, Picture3: Picture3, Start: startdate, ETA: 
      ETADate} 

     ProductsArray.push(ProductEntry); 

     localStorage.setItem("Product", JSON.stringify(ProductsArray)); 

在我試圖檢索數組我jQuery代碼是視圖:

$("#SearchButton").click(function(){ 
     var SearchQuery = document.getElementById("SearchField").value; 
     var storageObject = JSON.parse(localStorage.getItem("Product")); 
     alert(storageObject[1].Title);   
    }); 

上面,我我試圖訪問ProductEntry對象的屬性'Title'。我哪裏錯了?從該項目的C#MVC環境切換。

回答

0

問題是您嘗試創建的ProductEntry不是有效的JSON。

試試這個代碼:

var ProductEntry = [{Title: 'ProductTitle', Description: 'Description', Hashtags: 'Hashtags', 
       Picture1: 'Picture1', Picture2: 'Picture2', Picture3: 'Picture3', Start: 'startdate', ETA: 
       'ETADate'}] 

      localStorage.setItem("Product", JSON.stringify(ProductEntry)); 

$("#SearchButton").click(function(){ 
     var SearchQuery = document.getElementById("SearchField").value; 
     var storageObject = JSON.parse(localStorage.getItem("Product")); 
     alert(storageObject[0].Title);   
    }); 
+0

工作!謝謝!什麼構成了有效的JSON?你是否可以將我鏈接到一些文檔,因爲我是新手。 –

+0

@AlimCharaniya好的,https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON是JSON的官方頁面,如果t對你有幫助,請接受我的回答。 –

+0

實際上,我發現你在JSON中傳遞的每個對象屬性都是一個文字,如果我想將變量傳遞給對象的每個屬性,該怎麼辦? –

相關問題