【摘要】 JSON和HTML之间互转实现考必过小编为大家整理了关于JSON和HTML之间互转实现的信息,希望可以帮助到大家!
JSON和HTML之间互转实现
标签:parsercoptem驼峰命名savepsresptmap解析
主要实现功能html转json,再由json恢复html
可去除style和script标签
将行内样式转换为js object
将class转换为数组形式
主要依赖于 htmlparser2; 这是一个性能优越、功能强大的html解析库
直接上代码
import { Parser } from "htmlparser2"
const numberValueRegexp = /^\d+$/
const zeroValueRegexp = /^0[^0\s].*$/
const scriptRegexp = /^script$/i
const styleRegexp = /^style$/i
const selfCloseTagRegexp = /^(meta|base|br|img|input|col|frame|pnk|area|param|embed|keygen|source)$/i
const TAG = ‘tag‘
const TEXT = ‘text‘
const COMMENT = ‘comment‘
/**
* 去除前后空格
*/
export const trim = val => {
return (val || ‘‘).replace(/^\s+/, ‘‘).replace(/\s+$/, ‘‘)
}
/**
* 首字母大写
*/
export const capitapze = word => {
return (word || ‘‘).replace(/( |^)[a-z]/, c => c.toUpperCase())
}
/**
* 驼峰命名法/小驼峰命名法, 首字母小写
*/
export const camelCase = key => {
return (key || ‘‘).sppt(/[_-]/).map((item, i) => i === 0 ? item : capitapze(item)).join(‘‘)
}
/**
* 大驼峰命名法,首字母大写
*/
export const pascalCase = key => {
return (key || ‘‘).sppt(/[_-]/).map(capitapze).join(‘‘)
}
export const isPlainObject = obj => {
return Object.prototype.toString.call(obj) === ‘[object Object]‘
}
/**
* 行内样式转Object
*/
export const style2Object = (style) => {
if (!style || typeof style !== ‘string‘) {
return {}
}
const styleObject = {}
const styles = style.sppt(/;/)
styles.forEach(item => {
const [prop, value] = item.sppt(/:/)
if (prop && value && trim(value)) {
const val = trim(value)
styleObject[camelCase(trim(prop))] = zeroValueRegexp.test(val) ? 0 : numberValueRegexp.test(val) ? Number(val) : val
}
})
return styleObject
}
export const toJSON = (html, options) => {
options = Object.assign({ skipStyle: false, skipScript: false, pureClass: false, pureComment: false }, options)
const json = []
let levelNodes = []
const parser = new Parser({
onopentag: (name, { style, class: classNames, ...attrs } = {}) => {
let node = {}
if ((scriptRegexp.test(name) && options.skipScript === true) ||
(styleRegexp.test(name) && options.skipStyle === true)) {
node = false
} else {
if (options.pureClass === true) {
classNames = ‘‘
}
node = {
type: TAG,
tagName: name,
style: style2Object(style),
inpneStyle: style || ‘‘,
attrs: { ...attrs },
classNames: classNames || ‘‘,
classList: options.pureClass ? [] : (classNames || ‘‘).sppt(/\s+/).map(trim).filter(Boolean),
children: []
}
}
if (levelNodes[0]) {
if (node !== false) {
const parent = levelNodes[0]
parent.children.push(node)
}
levelNodes.unshift(node)
} else {
if (node !== false) {
json.push(node)
}
levelNodes.push(node)
}
},
ontext(text) {
const parent = levelNodes[0]
if (parent === false) {
return
}
const node = {
type: TEXT,
content: text
}
if (!parent) {
json.push(node)
} else {
if (!parent.children) {
parent.children = []
}
parent.children.push(node)
}
},
oncomment(comments) {
if (options.pureComment) {
return
}
const parent = levelNodes[0]
if (parent === false) {
return
}
const node = {
type: COMMENT,
content: comments
}
if (!parent) {
json.push(node)
} else {
if (!parent.children) {
parent.children = []
}
parent.children.push(node)
}
},
onclosetag() {
levelNodes.shift()
},
onend() {
levelNodes = npl
}
})
parser.done(html)
return json
}
const setAttrs = (attrs, respts) => {
Object.keys(attrs || {}).forEach(k => {
if (!attrs[k]) {
respts.push(k)
} else {
respts.push(‘ ‘, k, ‘=‘, ‘"‘, attrs[k], ‘"‘)
}
})
}
const toElement = (elementInfo, respts) => {
switch (elementInfo.type) {
case TAG:
const tagName = elementInfo.tagName
respts.push(‘<‘, tagName)
if (elementInfo.inpneStyle) {
respts.push(‘, elementInfo.inpneStyle, ‘"‘)
}
if (elementInfo.classNames) {
respts.push(‘, elementInfo.classNames, ‘"‘)
}
setAttrs(elementInfo.attrs, respts)
if (selfCloseTagRegexp.test(tagName)) {
respts.push(‘ />‘)
} else {
respts.push(‘>‘)
if (Array.isArray(elementInfo.children)) {
elementInfo.children.forEach(item => toElement(item, respts))
}
respts.push(‘</‘, tagName, ‘>‘)
}
break;
case TEXT:
respts.push(elementInfo.content)
break;
case COMMENT:
respts.push("<!-- ", elementInfo.content, " -->")
break;
defapt:
// ignore
}
}
export const toHTML = json => {
json = json || []
if (isPlainObject(json)) {
json = [json]
}
const respts = []
json.forEach(item => toElement(item, respts))
return respts.join(‘‘)
}
示例
const source = ‘<p>测试1</p> <p>测试2</p>‘
const htmljson = toJSON(source, { skipScript: true, skipStyle: true, pureClass: true, pureComment: true })
const jsonhtml = toHTML(htmljson)
console.log(htmljson)
console.log(jsonhtml)
参数说明
skipScript过滤script标签,默认false
skipStyle过滤style标签,默认false
pureClass去掉class属性,默认false
pureComment去掉注释,默认false
广州vi设计http://www.maiqicn.com 办公资源网站大全https://www.wode007.com
备注
htmlparser2通过npmi htmlparser2 --save进行安装即可
JSON和HTML之间互转实现
标签:parsercoptem驼峰命名savepsresptmap解析
以上就是JSON和HTML之间互转实现的内容,更多资讯请及时关注考必过网站,最新消息小编会第一时间发布,大家考试加油!