2012-02-23 38 views
0

我知道我可以創建這個JSON:如何使用JavaScript和數據集創建JSON?

[ 
    { 
     "Title": "Something", 
     "Price": "234", 
     "Product_Type": "dsf sf" 
    }, 
    { 
     "Title": "hskiuea", 
     "Price": "4234", 
     "Product_Type": "sdawer" 
    } 
] 

*它使用從包含與類「newpappend」的元素中的文本輸入中獲得的值 - 如下圖所示

使用以下代碼從我的HTML獲得的值:

var jsonObj = []; //declare array 


$(".newpappened").each(function() { 

    var p_title = $(this).find('#p_title').val(); 
    var p_price = $(this).find('#p_price').val(); 
    var p_ptype = $(this).find('#p_ptype').val(); 

    jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype}); 
    $(this).remove(); 
}); 

但是,我的目標是構建這樣的JSON落得:

{ 
    "Product_List": { 
     "Product": [ 
      { 
       "Title": "asdf", 
       "Price": "53", 
       "Product_Type": "Adfsdf" 
      }, 
      { 
       "Title": "asgsd", 
       "Price": "123", 
       "Product_Type": "Ntohig" 
      } 
     ] 
    } 
} 

基本上,我正在努力使用正確的Javascript來達到我的目標

回答

3

你真的很接近。從你有什麼開始,然後:

var output = { 
    "Product_List": { 
     "Product": jsonObj 
    } 
} 
// output is now what you are looking for. 
+0

哇,這很簡單。謝謝你的快速,簡單,和好的答案:) – TaylorMac 2012-02-23 05:51:15

+0

將接受5 – TaylorMac 2012-02-23 05:51:20

+0

然後'JSON.stringify(輸出)'如果你真的想要JSON而不是一個對象... – nnnnnn 2012-02-23 06:05:57