2014-11-21 136 views
-1

我在像這樣的代碼初始化一個JSON文件:將元素添加到JSON文檔

var json = []; 

我用的是'.push()方法將元素添加到該文件是這樣的:

json.push({title: "abc", link: "xxx"}); 

最後我得到一個JSON文件,看起來像這樣:

[ 
    { 
    "title": "abc", 
    "link": "xxx" 
    } 
    { 
    "title": "asd", 
    "link": "zzz" 
    } 
    ... 
] 

這並不完全是壞事,但我希望它看起來像這樣:

{ 
    "links": 
    [ 
     { 
     "title": "abc", 
     "link": "xxx" 
     } 
     { 
     "title": "asd", 
     "link": "zzz" 
     } 
     ... 
    ] 
} 

任何想法,我可以做到這一點?

回答

1

這樣做

var json = []; 

您初始化數組,而不是一個對象。

爲了有一個對象,你可以這樣做:

var json = {}; 

然後添加一個字段:

json.links = []; 

然後推入你的鏈接對象:

json.links.push({title: "abc", link: "xxx"}); 
+0

請稍候... – dsljanus 2014-11-21 08:28:23

0
var json = {}; 
json.links = []; 
json.links.push({title: "abc", link: "xxx"}); 
0
var json = { 
    links: [] 
}; 
json.links.push({title: "abc", link: "xxx"});