bash 将纯文本转换为json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25284778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting plain text into json
提问by user1611830
Suppose I have a text file that I want to convert into json file. Precisely, I want to convert each line $line
to "$line":"someid"
. Is there a proper way to do that using bash script langage or javascript
.
假设我有一个要转换为 json 文件的文本文件。准确地说,我想将每一行转换$line
为"$line":"someid"
. 是否有使用 bash 脚本语言或javascript
.
For example
例如
I want to
convert
text into
json
would output
会输出
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}
回答by Andy
You can't do your expected output like that because you will produce a syntax error, but you can put multiple objects in an arrayinstead. Something like this:
你不能像那样做你预期的输出,因为你会产生一个语法错误,但你可以把多个对象放在一个数组中。像这样的东西:
HTML
HTML
<div id="id">
I want to
convert
text into
json
</div>
JS
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);