使用Htmlparser2将以下html转换为json <tbody> <tr> <td><input type="checkbox" v-model="RemitInBox" class="RemitInBox v-pristine v-valid" name="RemitInBox" value="0" v-checked="data.CheckFlag" v-disabled="data.FndDrc!='01' || data.BusiState!='10'" id="List0_RemitIn" v-click="clickBox($index,data)"></td> <td><span v-show="data.FndDrc!='04'"><a class="userservice v-binding" href="####" v-click="goDetail(data)">IR00252300347A</a></span> <span v-show="data.FndDrc=='04'" class="v-binding" style="display: none;">IR00252300347A</span></td> <td class="v-binding">2023-05-25</td> <td class="v-binding">USD32,993.50</td> <td class="v-binding">1/FLOKSER KIMYA SANAYI VE TICARET 1...</td> <td class="v-binding">31980005000107125</td> <td><span v-show="data.FndDrc=='01'">入账</span> <span v-show="data.FndDrc=='04'" style="display: none;">退汇</span> <span v-show="!(data.FndDrc=='04'||data.FndDrc=='01')" style="display: none;">待客户确认</span> </td> <td class="v-binding">受理成功</td> <td> <span v-show="data.FndDrc=='01' && data.BusiState=='10'"> <a href="#" v-click="remitInPrint(data.BsnSrlNo)" class="userservice"> 打印 </a> </span> </td> </tr> </tbody>
时间: 2023-08-14 21:13:18 浏览: 147
html-to-json:将HTML转换为JSON。 还可以(智能地)将HTML表转换为JSON(使用表头(如果有)作为结果JSON中的键)
使用Htmlparser2将HTML转换为JSON需要经过以下步骤:
1. 安装Htmlparser2库:
```
npm install htmlparser2
```
2. 引入Htmlparser2库:
```
const htmlparser = require('htmlparser2');
```
3. 定义一个解析器对象:
```
const parser = new htmlparser.Parser({
onopentag: function(name, attribs){
// 处理开始标签
},
ontext: function(text){
// 处理文本节点
},
onclosetag: function(tagname){
// 处理结束标签
}
}, {decodeEntities: true});
```
4. 将HTML文档传递给解析器对象:
```
parser.write(html);
parser.end();
```
5. 在回调函数中处理解析结果:
```
const result = [];
let current = null;
parser.onopentag = function(name, attribs) {
if (name === 'tr') {
current = {};
} else if (name === 'td') {
const className = attribs.class;
if (className === 'v-binding') {
current[attribs.class] = '';
} else if (className === 'RemitInBox v-pristine v-valid') {
current[attribs.class] = attribs.value;
}
} else if (name === 'a') {
current['IR'] = attribs.class === 'userservice v-binding' ? attribs.href : '';
}
};
parser.ontext = function(text) {
if (current) {
const keys = Object.keys(current);
const lastKey = keys[keys.length - 1];
current[lastKey] += text.trim();
}
};
parser.onclosetag = function(tagname) {
if (tagname === 'tr') {
result.push(current);
current = null;
}
};
console.log(result);
```
这段代码将HTML中的表格数据转换为了JSON格式,每行数据都是一个对象,属性名对应表格中的列名。注意,在这个例子中,为了简化代码,只处理了表格中的部分列,您可能需要根据具体情况进行调整。
阅读全文