最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - converting plain text into json - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 4

You 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

发布评论

评论列表(0)

  1. 暂无评论