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
.
For example
I want to
convert
text into
json
would output
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}
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
.
For example
I want to
convert
text into
json
would output
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}
Share
Improve this question
asked Aug 13, 2014 at 11:19
user1611830user1611830
4,86312 gold badges55 silver badges92 bronze badges
1 Answer
Reset to default 4You can't do your expected output like that because you will produce a syntax error, but you can put multiple objects in an array instead. Something like this:
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);
DEMO
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131354a4612987.html
评论列表(0条)