#javascript #json #text
#javascript #json #текст
Вопрос:
Я считываю данные о сотрудниках из текстового файла, как показано ниже.
$( 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. ожидаемый результат — недопустимый json.
2. значит, после каждой строки есть символ возврата (r или n ?) и после каждой записи есть два разрыва строки?
3. @Jenz — так почему же тогда вы показали его с помощью символов
n
илиr
? Показанный вами файл ответов содержит один или оба.4. Как мы можем определить двойной разрыв .. Я пытался путем разделения с помощью
rn
, но это не дает никакого результата.5. @Jenz — посмотрите на файл в шестнадцатеричном редакторе и посмотрите, что в нем содержится, зачем гадать, когда можно посмотреть? 0x0A для CR или r, 0x0D для LF или n
Ответ №1:
Этот пример, протестированный с div, содержит ваш текст в HTML, и когда мы получаем innerText
это, возвращаются блоки, на которые мы можем разделить его nn
//split using nn
function toJson(str) {
var tt = [];
var rw = str.split("nn");
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>