【5】Vite+Vue3 JsonPath的使用

本文介绍了Vite和Vue3的组合在前端开发中的优势,包括快速启动和高效开发体验。通过100+实战示例,读者可以学习如何使用Vite搭建项目,掌握Vue3的语法和特性,以及JsonPath在处理JSON数据中的作用和用法。文章还提供了公共方法的封装示例,帮助开发者更便捷地操作JSON数据。
摘要由CSDN通过智能技术生成

在当今前端开发的领域里,快速、高效的项目构建工具以及使用最新技术栈是非常关键的。Vite+Vue3 组合为一体的项目实战示例专栏将带领你深入了解和掌握这一最新的前端开发工具和框架。

作为下一代前端构建工具,Vite 在开发中的启动速度和热重载方面具有突出的优势。而Vue3,则以更加简化的API和更高效的响应式系统为开发者带来了更加流畅的开发体验。结合使用Vite和Vue3,你将能够快速搭建稳定、高效的前端项目。

在这个专栏里,我们将通过100+个实战示例,详细介绍Vite+Vue3的各个方面。从项目的创建和配置开始,我们会一步一步地引导你使用Vite搭建项目的基本框架,并深入讲解Vue3的语法和特性。随后,我们将演示如何构建常见的前端组件、路由管理和状态管理,以及与后端API的交互等实际项目开发中常见的场景。

无论你是从零开始学习Vite+Vue3,还是希望进一步提升你的前端开发能力,本专栏都能为你提供实用的知识和实战经验。通过这100+个实战示例的学习,你将能够掌握Vite+Vue3的核心概念和技术,并能够在实际项目中灵活应用。

赶快加入我们吧,开始你的Vite+Vue3项目实战之旅!

一、JsonPath是什么 ❔ ❔ ❔

JsonPath是一种用于查询和过滤JSON数据的语言。它类似于XPath,但专为处理JSON数据而设计。使用JsonPath,您可以根据预定义的语法模式从JSON数据中选择和提取特定的值或对象。它可以用于查找、过滤和提取JSON数据的任何部分,如属性、数组、嵌套对象等。通过指定路径表达式,您可以快速、简洁地定位JSON数据中的目标元素。

二、使用JsonPath的好处 ❔ ❔ ❔

1、简洁 🔥 🔥

使用JsonPath,您可以用短小的路径表达式准确地选择和提取JSON数据,而不需要编写复杂的循环和条件语句。

2、灵活 🔥 🔥

JsonPath支持多种操作符和筛选条件,使您能够灵活地过滤和操作JSON数据。

3、兼容性 🔥 🔥

JsonPath在许多编程语言和工具中都有实现,如JavaScript、Java、Python等,因此可以在不同环境中广泛使用。

总之,JsonPath是一种强大的工具,可以帮助前端开发人员更高效地处理和操作JSON数据。

三、演示数据 ✨ ✨ ✨

演示数据的话来自于JsonPath官网。对官网的使用案例再一次进行补充。

const source  = ref({
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        },
        "classify": {
            "Meat": ['鸡肉', '牛肉'],
            "fruit": ['苹果', '牛油果'],
        },
    }
})

使用方法 ✨ ✨ ✨

JSONPath({
    path: `$.store.*`,
    json: source.value,
    resultType: 'value',
})

参数说明 ✨ ✨ ✨

json的话就是数据源

path

path是用来指定要提取的JSON数据的位置。它由层级结构的键和运算符组成,用于导航和过滤JSON数据。

$根节点
$.key选择根节点下名为"key"的键
$.key1.key2选择根节点下名为"key1"的键的值中的名为"key2"的键
$.array[0]选择根节点下名为"array"的键的值中的索引为0的元素
$.array[*]选择根节点下名为"array"的键的值中的所有元素
$.array[?(@.key == "value")]选择根节点下名为"array"的键的值中,具有键"key"的值等于"value"的元素

resultType

value返回匹配结果的值。
path返回匹配结果的路径。
all返回匹配结果的值和路径。
pointer返回匹配结果的JSON指针。
parent返回匹配结果的父节点。
parentProperty返回匹配结果的父节点的属性名。

1、获取store下的所有数据 👇 👇

JSONPath({
    path: `$.store.*`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [Proxy(Array), Proxy(Object), Proxy(Object)]

2、获取book下的所有数据 👇 👇

JSONPath({
    path: `$.store.book.*`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [Proxy(Object), Proxy(Object), Proxy(Object), Proxy(Object)]
JSONPath({
    path: `$...book.*`, // `$...book[*]`
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [Proxy(Object), Proxy(Object), Proxy(Object), Proxy(Object)]

3、获取book数组中的数据 👇 👇

3.1、获取book中的指定元素

// book[*]代表 book下的所有元素
JSONPath({
    path: `$.store.book[*].author`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => ['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']
// book[0]代表 book下的第一个元素
JSONPath({
    path: `$.store.book[0].author`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => ['Nigel Rees']

3.2、获取book最后一个元素

JSONPath({
    path: `$.store.book[(@.length-1)]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
JSONPath({
    path: `$.store.book[-1:]]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]

3.3、获取起始下标到结束下标之间的数据

JSONPath({
    path: `$.store.book[0,1]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
JSONPath({
    path: `$.store.book[:2]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99}]

3.4、获取book第一个元素中的指定属性对应的值

// 获取book第一个元素中的指定属性对应的值
JSONPath({
    path: `$.store.book[0][category,author]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => ["reference","Nigel Rees"]

3.5、获取book中含有指定属性(指定属性值不为空)的元素

JSONPath({
    path: `$.store.book[?(@.isbn)]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]

3.6、获取book中price属性值小于10的

JSONPath({
    path: `$.store.book[?(@.price<10)]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99}]

4、正则匹配book下key值是bn结尾的元素 👇 👇

JSONPath({
    path: `$..book.*[?(@property.match(/bn$/i))]^`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})

5、正则获取store下key包含class的元素 👇 👇

JSONPath({
    path: `$.store[?(@property.match(/class/i))]`,
    json: source.value,
    resultType: 'value', // value、path、all、pointer、parent、parentProperty
})
// => [{"Meat":["鸡肉","牛肉"],"fruit":["苹果","牛油果"]}]

四、公共方法的封装 ✨ ✨ ✨ 

经过上面的使用方法以后,每次都要写这么,比较麻烦,在观察使用的规则以后,我封装了一个基本能符合大部分使用规则的公共方法。

const universalMatcher = (field: NamePath | NamePath[]) => {
    const fieldType = getType(field)
    if (fieldType === "string" || fieldType === 'number') {
        return field
    }
    // 这里按道理来说field本身就是(string | number)[],但是我的编辑器好像有点蠢,我只能再通过as断言一下
    let result: string = '';
    (field as (string | number)[]).forEach(item => {
        const itemType = getType(item)
        if (itemType === "string") {
            result += `${item}.`
        } else if (itemType === "number") {
            if (!result) {
                throw {
                    code: -1,
                    msg: 'The input parameters do not match'
                }
            }
            result = removeLastPoint(result) + `[${item}].`
        }
    })
    return removeLastPoint(result)
}

const removeLastPoint = (source: string) => {
    return (source && source.endsWith('.')) ? source.substring(0, source.length - 1) : source
}

const getJsonPathData = (field: NamePath | NamePath[], type: 'value'|'path'|'all'|'pointer'|'parent'|'parentProperty' = 'value') => {
    return JSONPath({
        path: `$.${universalMatcher(field)}`,
        json: source.value,
        resultType: type,
    })
}

使用 ✨ ✨ ✨ 

onMounted(() => {
    console.log('👉👉👉-----------------', JSON.stringify(getJsonPathData(['store', 'book[(@.length-1)]'])))
    // => [{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
    
    console.log('👉👉👉-----------------', JSON.stringify(getJsonPathData(['store[?(@property.match(/class/i))]'])))
    // => [{"Meat":["鸡肉","牛肉"],"fruit":["苹果","牛油果"]}]
    
    console.log('👉👉👉-----------------', JSON.stringify(getJsonPathData(['store', 'book', 0, 'author'])))
    // => ["Nigel Rees"]
    
    console.log('👉👉👉-----------------', JSON.stringify(getJsonPathData(['store', 'book[0]', 'author'])))
    // => ["Nigel Rees"]
    
    console.log('👉👉👉-----------------', JSON.stringify(getJsonPathData(['store', 'book[0]', 'author'], "all")))
    // => [{"path":"$['store']['book'][0]['author']","value":"Nigel Rees","parent":{"category":"reference","author":"Nigel Rees","title":"Sayings of the Centu
    
    console.log('👉👉👉-----------------', JSON.stringify(getJsonPathData(['store', 'book[0]', 'author'], "path")))
    // => ["$['store']['book'][0]['author']"]
})

我是Etc.End。每一次进步都值得庆祝,每一次努力都值得赞赏。不要忽视自己的成长,每一步都是向前迈进的力量。如果我的文章对你有所帮助的话,希望能留下你的点赞和收藏。😍。

👇 👇 👇 👇 👇 👇 👇 👇 👇 👇 👇 👇

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Etc.End

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值