假设我有一个文本文件,我想将其转换为 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);
关于javascript - 将纯文本转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25284778/