美文网首页
jsonpath 2022-01-16

jsonpath 2022-01-16

作者: 9_SooHyun | 来源:发表于2022-01-15 15:30 被阅读0次

    jsonpath是用于解析json文件的强大工具,不同语言都有各自的实现

    jsonpath的设计思想正则表达式相似

    • 首先构建一个【jsonpath表达式】,或者说pattern
    • 使用该表达式在json object中匹配结果

    jsonpath in python

    python的jsonpath_rw使用类似正则表达式的方式,构建一个jsonpath_expr,然后用该expr去匹配json object,返回匹配的对象

    jsonpath in golang

    github.com/oliveagle/jsonpath也是类似的
    以下例子来自readme
    json data:

    {
        "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
            }
        },
        "expensive": 10
    }
    

    code

    import (
        "github.com/oliveagle/jsonpath"
        "encoding/json"
    )
    
    var json_data interface{}
    json.Unmarshal([]byte(data), &json_data)
    
    // "$.expensive" is a jsonpath_expr
    res, err := jsonpath.JsonPathLookup(json_data, "$.expensive")
    
    //---or reuse lookup pattern---
    // Compile returns a jsonpath_expr, which is looked up in target json object
    pat, _ := jsonpath.Compile(`$.store.book[?(@.price < $.expensive)].price`)
    res, err := pat.Lookup(json_data)
    

    相关文章

      网友评论

          本文标题:jsonpath 2022-01-16

          本文链接:https://www.haomeiwen.com/subject/ylmfhrtx.html