2015-02-06 115 views
-3

我有一個簡單的var,其中有一些字符串轉換爲json對象。我想爲人名輸入字段,然後添加文本。在json字符串中傳遞一個變量

目前我有這個

var text = '{"students":[' + 
'{"firstName": "Brendan","lastName":"Skousen" },' + 
'{"firstName":"Scooby","lastName":"Doo" },' + 
'{"firstName":"Your","lastName":"Mom" }]}'; 

,我有一個變種我輸入

var first = document.getElementById('first').value; 

所以我想有VAR文字工作是這樣的:

var text = '{"students":[' + 
'{"firstName": first,"lastName":"Skousen" },' + 
'{"firstName": first,"lastName":"Norman" },' + 
'{"firstName": first,"lastName":"Coatney" }]}'; 

你可以看到完整的代碼:http://codepen.io/bskousen/pen/xbPLew

+3

使用'JSON.parse',改變它''JSON.stringify' – Dom 2015-02-06 21:59:48

回答

0
var text = '{"students":[' + 
'{"firstName": ' + escape(first) + ',"lastName":"Skousen" },' + 
'{"firstName": ' + escape(first) + ',"lastName":"Norman" },' + 
'{"firstName": ' + escape(first) + ',"lastName":"Coatney" }]}'; 

使用escapehere

0

爲了使它在你的例子中使用它的方式,你將不得不使用template engine並根據你使用的引擎在變量周圍添加一些額外的字符。我認爲連接會對你的情況最容易

var text = '{"students":[' + 
'{"firstName": ' + first + ',"lastName":"Skousen" },' + 
'{"firstName": ' + first + ',"lastName":"Norman" },' + 
'{"firstName": ' + first + ',"lastName":"Coatney" }]}'; 
相關問題