[英]converting plain text into json
假設我有一個想要轉換為json文件的文本文件。 准確地說,我想將每行$line
轉換為"$line":"someid"
。 是否有使用bash腳本語言或javascript
的正確方法。
例如
I want to
convert
text into
json
將輸出
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}
您不能那樣做預期的輸出,因為會產生語法錯誤,但是可以將多個對象放在數組中 。 像這樣:
HTML
<div id="id">
I want to
convert
text into
json
</div>
JS
var textArr = document.querySelector('#id').innerHTML.split('\n');
function produceJSON(textArr) {
var arr = [];
// we loop from 1 to 1 less than the length because
// the first two elements are empty due to the way the split worked
for (var i = 1, l = text.length - 1; i < l; i++) {
var obj = {};
obj[text[i]] = i;
arr.push(obj);
}
return JSON.stringify(arr);
}
var json = produceJSON(textArr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.