代码之家  ›  专栏  ›  技术社区  ›  Johan

BigQuery支持哪些JsonPath表达式?

  •  2
  • Johan  · 技术社区  · 8 年前

    我读了BigQuery documentation JsonPath 表达语言。但我找不到JsonPath的哪些部分实际上是

    1. 是否有参考文件或其他文件描述 满的
    2 回复  |  直到 8 年前
        1
  •  10
  •   marc_s MisterSmith    7 年前

    为了克服JsonPath的BigQuery“限制”,可以引入 custom function
    注意:它使用jsonpath-0.8.0。js,可从 https://code.google.com/archive/p/jsonpath/downloads

    #standardSQL
    CREATE TEMPORARY FUNCTION CUSTOM_JSON_EXTRACT(json STRING, json_path STRING)
    RETURNS STRING
    LANGUAGE js AS """
        try { var parsed = JSON.parse(json);
            return JSON.stringify(jsonPath(parsed, json_path));
        } catch (e) { return null }
    """
    OPTIONS (
        library="gs://your_bucket/jsonpath-0.8.0.js"
    );
    WITH t AS (
    SELECT '''
    { "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
            }
        }
    }
    ''' AS x
    )
    SELECT 
        CUSTOM_JSON_EXTRACT(x, '$.store.book[*].author'),
        CUSTOM_JSON_EXTRACT(x, '$..*[?(@.price==22.99)].author'),
        CUSTOM_JSON_EXTRACT(x, '$..author'),
        CUSTOM_JSON_EXTRACT(x, '$.store.*'),
        CUSTOM_JSON_EXTRACT(x, '$.store..price'),
        CUSTOM_JSON_EXTRACT(x, '$..book[(@.length-1)]'),
        CUSTOM_JSON_EXTRACT(x, '$..book[-1:]'),
        CUSTOM_JSON_EXTRACT(x, '$..book[0,1]'),
        CUSTOM_JSON_EXTRACT(x, '$..book[:2]'),
        CUSTOM_JSON_EXTRACT(x, '$..book[?(@.isbn)]')
    FROM t
    

    结果如下

    CUSTOM_JSON_EXTRACT(x, '$.store.book[*].author')

    [
      "Nigel Rees"
      "Evelyn Waugh"
      "Herman Melville"
      "J. R. R. Tolkien"
    ]
    

    对于 CUSTOM_JSON_EXTRACT(x, '$..*[?(@.price==22.99)].author')

    [
      "J. R. R. Tolkien"
    ]  
    

    CUSTOM_JSON_EXTRACT(x, '$.store..price')

    [
      8.95
      12.99
      8.99
      22.99
      19.95
    ]
    

    等等

        2
  •  3
  •   Elliott Brossard    8 年前

    支持的元素位于链接到的节的表中。具体来说,它包括 $ , . [] ,其中后者可以是子运算符或下标(数组)运算符。如果未列出,则不支持。