读取文本文件并以特定格式转换为JSON

时间:2016-10-24 13:12:34

标签: javascript json text

我正在通过如下所示的文本文件阅读员工详细信息。

$( document ).ready(function() {
    $.ajax({
        url: "employees.txt",
        success:function(response) {
            console.log(response);
        }
    });
});

它给我的反应如下:

    Mark
    Mark have 10 years of experience working with youth agencies. Mark have a bachelor’s degree in outdoor education. He raise money, train leaders, and organize units. He have raised over $100,000 each of the last six years. He consider himself a good public speaker, and have a good sense of humor.

    Jennifer
    Jennifer enjoy meeting new people and finding ways to help them have an uplifting experience. She have had a variety of customer service opportunities, through which she was able to have fewer returned products and increased repeat customers, when compared with co-workers. She is dedicated, outgoing, and a team player.

现在从这个回复我需要一个结果结构,如:

 var employees = [
   ["mark", {
      "name": "Mark",
      "description": "Mark have 10 years of experience working with youth agencies. Mark have a bachelor’s degree in outdoor education. He raise money, train leaders, and organize units. He have raised over $100,000 each of the last six years. He consider himself a good public speaker, and have a good sense of humor."
   }],
   ["jennifer", {
      "name": "Jennifer",
      "description": "Jennifer enjoy meeting new people and finding ways to help them have an uplifting experience. She have had a variety of customer service opportunities, through which she was able to have fewer returned products and increased repeat customers, when compared with co-workers. She is dedicated, outgoing, and a team player."
   }]
];

我该怎么做?任何人都可以帮我这样做吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用div测试的此示例包含HTML格式的文本,当我们获得innerText时,会返回我们可以将其拆分为\n\n

的块

//split using \n\n

function toJson(str) {
  var tt = [];
  var rw = str.split("\n\n");
  for (var i = 0; i < rw.length; i++) {
    var name = rw[i].split("\n")[0].trim();
    var description = rw[i].split("\n")[1].trim();
    var jsn = [
      name, {
        "name": name,
        "description": description
      }
    ]
    tt.push(jsn);
  }
  return tt;
}

var employees = toJson(document.getElementById("txt").innerText);

console.log(employees);
<div id='txt'>
  Mark
  <br/>Mark have 10 years of experience working with youth agencies. Mark have a bachelor’s degree in outdoor education. He raise money, train leaders, and organize units. He have raised over $100,000 each of the last six years. He consider himself a good
  public speaker, and have a good sense of humor.
  <br/>
  <br/>Jennifer
  <br/>Jennifer enjoy meeting new people and finding ways to help them have an uplifting experience. She have had a variety of customer service opportunities, through which she was able to have fewer returned products and increased repeat customers, when compared
  with co-workers. She is dedicated, outgoing, and a team player.
</div>