簡體   English   中英

JavaScript將數組轉換為JSON格式

[英]JavaScript convert array to JSON format

我有一個像

["categories", 1, "categories", 2, "categories", 3]

我想將此數組轉換為JSON格式,例如

{"categories":1,"categories":2, "categories":3}

您可以使用以下方法將數組轉換為JSON:

var a = ["categories", 1, "categories", 2, "categories", 3];
var json = JSON.stringify(a);
// json will be: "["categories",1,"categories",2,"categories",3]"

您在問題中使用的JSON字符串不是數組,而是一個對象。 正如Pranav在其評論中指出的那樣,它是無效的對象表示法,因為對象的屬性必須唯一。

在這種情況下,我們將必須經過{"categories": [1,2,3]} 為此,我們必須創建一個值數組並創建一個JSON數據{"categories": [1,2,3]}

這解決了通過ajax發布同一字段的多個值(如復選框)的問題。

如果你是這個意思

["categories1", 1, "categories2", 2, "categories3", 3]

每個鍵都不同,那么您可以使用

var a = ["categories1", 1, "categories2", 2, "categories2", 3],
    b = {}, len = a.length;

for(i=0; i<len; i+=2){
    var key = a[i], val = a[i+1];
    b[key] = val
}

// b should be {"categories1":1,"categories2":2, "categories3":3}

否則,就像@Pranav C Balan所說的那樣,您不能在一個對象中擁有三個相同的鍵,它們只會覆蓋先前的鍵;

您可能還需要此下划線方法,非常方便

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM