我使用JavaScript和循環通過提交的表單的值,並試圖建立一個兒子對象的形式值。javascript將JSON字符串轉換爲JSON對象
這是最終目標的一個例子,我需要:
{
"DataObject": {
"user": { "-name": "username" },
"contentFile": {
"-filename": "Breaking_News",
"lock": { "-fileIsBeingEdited": "false" },
"content": {
"line": [
{
"-index": "1",
"-text": "this is the header"
},
{
"-index": "2",
"-text": "this is the first line"
},
{
"-index": "3",
"-text": "this is the second line"
}
]
}
}
}
}
到目前爲止,我加入了所有這些數據的字符串作爲,這似乎是我可以插入表單值的唯一方法(在線陣列)到對象的中間。
var jsonStr = '{'
+ 'iceteaDataObject: {'
+ 'user: {"-name": "hindsc52"},'
+ 'contentFile: {'
+ '"-filename": "Ticker",'
+ 'lock: { "-fileIsBeingEdited": "false" },'
+ 'content: {'
+ 'line: ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += "-index: " + i + ',';
jsonStr += "-text: " + elem[i].value;
jsonStr += '},'
}
}
jsonStr += ']}}}}';
console.log(JSON.parse(jsonData));
但是,當運行這個我得到的錯誤:意外的令牌'我'。
我試圖用力地使用,但只是再次輸出整個sting。
檢查字符串的格式,這是不正確。將代碼粘貼到JSONLint中並查看錯誤 – Tushar
因爲您的第一條指令沒有結束,所以您需要在'for'循環之前添加一個額外的';'。 –
你不應該這樣創建一個JSON字符串。如果表單字段的值包含''',那麼它將會失敗,除了JSON格式的鍵需要被'''引用「,所以你根本不會創建一個有效的JSON字符串。意想不到的'i'是因爲你的鍵'iceteaDataObject'沒有被引用。創建一個普通的JavaScript對象並使用['JSON.stringify'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) –