• 技术文章 >Web开发 >JavaScript

    html转json

    小妮浅浅小妮浅浅2021-01-23 17:12:28原创5970

    json在存储的功能上一直受到很多人的追捧,除此之外由于适用的标点符号数目少,也减少一些不必要的字符使用。鉴于它的这些优点,我们是可以把html转换成json来用的。在正式开始之前,我们需要对json的概念有所了解,然后再进行代码模块的学习,下面我们来看看具体内容。

    1.json概念

    json(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它起源于JavaScript的数据对象,之后独立成为一种web较为流行的数据交换标准。

    json的语法,是非常明显的键值对结构,比较利于理解:

    1

    2

    3

    4

    5

    6

    7

    8

    {

      "note":{

            "to":"George",

            "from":"John",

            "heading":"Reminder",

            "body":"Don't forget the meeting!"

            }

    }

    2.实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

    76

    77

    78

    79

    80

    81

    82

    83

    84

    85

    86

    87

    88

    89

    90

    91

    92

    93

    94

    95

    96

    97

    98

    99

    100

    101

    102

    103

    104

    105

    106

    107

    108

    109

    110

    111

    112

    113

    114

    115

    116

    117

    118

    119

    120

    121

    122

    123

    124

    125

    126

    127

    128

    129

    130

    131

    132

    133

    134

    135

    136

    137

    138

    139

    140

    141

    142

    143

    144

    145

    146

    147

    148

    149

    150

    151

    152

    153

    154

    155

    156

    157

    158

    159

    160

    161

    162

    163

    164

    165

    166

    167

    168

    169

    170

    171

    172

    173

    174

    175

    176

    177

    178

    179

    180

    181

    182

    183

    184

    185

    186

    187

    188

    189

    190

    191

    192

    193

    194

    195

    196

    197

    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|link|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 capitalize = word => {

        return (word || '').replace(/( |^)[a-z]/, c => c.toUpperCase())

    }

    /**

     * 驼峰命名法/小驼峰命名法, 首字母小写

     */

    export const camelCase = key => {

        return (key || '').split(/[_-]/).map((item, i) => i === 0 ? item : capitalize(item)).join('')

    }

    /**

     * 大驼峰命名法,首字母大写

     */

    export const pascalCase = key => {

        return (key || '').split(/[_-]/).map(capitalize).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.split(/;/)

        styles.forEach(item => {

            const [prop, value] = item.split(/:/)

            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),

                        inlineStyle: style || '',

                        attrs: { ...attrs },

                        classNames: classNames || '',

                        classList: options.pureClass ? [] : (classNames || '').split(/\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 = null

            }

        })

        parser.done(html)

        return json

    }

    const setAttrs = (attrs, results) => {

        Object.keys(attrs || {}).forEach(k => {

            if (!attrs[k]) {

                results.push(k)

            } else {

                results.push(' ', k, '=', '"', attrs[k], '"')

            }

        })

    }

    const toElement = (elementInfo, results) => {

      

        switch (elementInfo.type) {

            case TAG:

                const tagName = elementInfo.tagName

                results.push('<', tagName)

                if (elementInfo.inlineStyle) {

                    results.push(' style="', elementInfo.inlineStyle, '"')

                }

                if (elementInfo.classNames) {

                    results.push(' class="', elementInfo.classNames, '"')

                }

                setAttrs(elementInfo.attrs, results)

                if (selfCloseTagRegexp.test(tagName)) {

                    results.push(' />')

                } else {

                    results.push('>')

                    if (Array.isArray(elementInfo.children)) {

                        elementInfo.children.forEach(item => toElement(item, results))

                    }

                    results.push('</', tagName, '>')

                }

                break;

            case TEXT:

                results.push(elementInfo.content)

                break;

            case COMMENT:

                results.push("<!-- ", elementInfo.content, " -->")

                break;

            default:

            // ignore

        }

    }

    export const toHTML = json => {

        json = json || []

        if (isPlainObject(json)) {

            json = [json]

        }

        const results = []

        json.forEach(item => toElement(item, results))

        return results.join('')

    }

    以上就是html转json的方法,其实json转html也同样适用,相当于本篇文章学习了两种转换的方法,看懂的小伙伴可以动手尝试了。

    专题推荐:html转json
    上一篇:html转jsp 下一篇:json在线解析怎么用

    相关文章推荐

    • html转jsp

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网