我的HTML模板有一点问题,无法转换为JSON。 我希望将HTML消息列表转换为JSON。提前感谢您的回复。
HTML模板
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Name</h4>
<span class="date">MM/DD/YYYY</span>
<span class="time">HH:MM</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Message here
</div>
</div>
</div>
<!-- Others .message -->
JSON渲染
{
"list": [
{
"pseudo": "Name",
"date": "MM/DD/YYYY",
"time": "HH:MM",
"message": "Message here"
},
/* ... */
]
}
答案 0 :(得分:2)
即使看起来不那么酷,我认为这会更快:
var pseudo = document.getElementsByClassName("pseudo");
var date = document.getElementsByClassName("date");
var time = document.getElementsByClassName("time");
var message = document.getElementsByClassName("message-text");
var list = [];
for(var i=0, l=pseudo.length;i<l;i++) {
list.push({
pseudo: pseudo[i].textContent,
data: date[i].textContent,
time: time[i].textContent,
message: message[i].textContent
})
}
console.log(list);
..取决于您的文件结构,这可能不是最佳解决方案
答案 1 :(得分:1)
您可以使用jQuery
从html
var result = [];
$(".message").each(function() {
var obj = {
pseudo: $(this).find(".pseudo").text(),
date: $(this).find(".date").text(),
time: $(this).find(".time").text(),
message: $(this).find(".message-text").text(),
};
result.push(obj);
})
console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Name</h4>
<span class="date">MM/DD/YYYY</span>
<span class="time">HH:MM</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Message here
</div>
</div>
</div>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">John</h4>
<span class="date">09/11/2011</span>
<span class="time">HH:MM</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
World Disaster
</div>
</div>
</div>
答案 2 :(得分:1)
只需获取所有.message
个元素,然后循环浏览它们以将其属性添加到结果数组中(我使用trim()
删除消息文本开头和结尾的多余空格):
console.log( messagesToJSON() );
function messagesToJSON(){
var messages = [],
elements = $('.message');
for(var i=0; i<elements.length; i++){
messages.push({
"pseudo": elements.eq(i).find('.pseudo').text(),
"date": elements.eq(i).find('.date').text(),
"time": elements.eq(i).find('.time').text(),
"message": elements.eq(i).find('.message-text').text().trim()
});
}
return {list: messages};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Kevin</h4>
<span class="date">08/01/2016</span>
<span class="time">14:52</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Hi there!
</div>
</div>
</div>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Robert</h4>
<span class="date">08/01/2016</span>
<span class="time">15:03</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Hello
</div>
</div>
</div>