简体   繁体   English

将纯文本转换为json

[英]converting plain text into json

Suppose I have a text file that I want to convert into json file. 假设我有一个想要转换为json文件的文本文件。 Precisely, I want to convert each line $line to "$line":"someid" . 准确地说,我想将每行$line转换为"$line":"someid" Is there a proper way to do that using bash script langage or javascript . 是否有使用bash脚本语言或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 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);

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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