简体   繁体   中英

converting plain text into json

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"}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM