javascript - 将纯文本转换为 json

标签 javascript json bash

假设我有一个文本文件,我想将其转换为 json 文件。准确地说,我想将每一行 $line 转换为 "$line":"someid" 。有没有正确的方法使用 bash 脚本语言或 javascript 来做到这一点。

例如

I want to
convert
text into
json

会输出

{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}

最佳答案

您不能像那样执行预期的输出,因为您会产生语法错误,但您可以将多个对象放入一个数组中。像这样的事情:

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

关于javascript - 将纯文本转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25284778/

相关文章:

javascript - 更改元素高度在第二次按下时不起作用

javascript - 如何在android的phonegap中使用rest web服务?

regex - 我如何使用 sed 搜索和替换而不包含一组字符?

javascript - 编写一个 React hook 来处理鼠标单击时的多个 div 可见性

javascript - AngularJS:超时 promise 调用

php - mysql获取数据的json响应

bash - 编写嵌套 shell 脚本 - 无法传递参数

regex - 使用正则表达式提取 OTP key

javascript - 如何在 Chrome 中通过 window.open 打开多个电子邮件客户端窗口?

javascript - 打印时嵌套 JSON 对象未显示