Expressão de caminho JSON

Aplica-se a: Marque Sim Databricks SQL Marque Sim Databricks Runtime

Uma expressão de caminho JSON é usada para extrair valores de uma cadeia de caracteres JSON ou usando VARIANT o operador :

Sintaxe

{ { identifier | [ field ] | [ * ] | [ index ] }
  [ . identifier | [ field ] | [ * ] | [ index ] ] [...] }

Os colchetes ao redor fieldde , * e index são colchetes reais e não indicam uma sintaxe opcional.

Parâmetros

  • identifier: um identificador de um campo JSON. Para tipos JSON STRING , o identificador não diferencia maiúsculas de minúsculas. Para VARIANT tipos, diferencia maiúsculas de minúsculas.
  • [ field ]: Um literal entre STRING colchetes que diferencia maiúsculas de minúsculas identificando um campo JSON.
  • [ * ]: Identificando todos os elementos em uma matriz JSON. Esta sintaxe não é suportada para VARIANT.
  • [ index ]: Um literal inteiro que identifica um elemento específico em uma matriz JSON baseada em 0.

Devoluções

A STRING se a expressão que está sendo navegada for um STRINGarquivo . A VARIANT se a expressão que está sendo navegada for um VARIANTarquivo .

Quando existir um campo JSON com um valor não delimitado null , você receberá um valor SQL NULL para essa coluna, não um valor de null texto.

Você pode usar :: operador para converter valores para tipos de dados básicos.

Use a função from_json para converter resultados aninhados em tipos de dados mais complexos, como matrizes ou estruturas.

Notas

Você pode usar um identificador não delimitado para fazer referência a um campo JSON se o nome não contiver espaços ou caracteres especiais e não houver nenhum campo no JSON STRING do mesmo nome em um caso diferente.

Use um identificador delimitado se não houver nenhum campo com o mesmo nome em um caso diferente.

A [ field ] notação sempre pode ser usada, mas requer que você corresponda exatamente ao caso do campo.

Se o Azure Databricks não puder identificar exclusivamente um campo, um erro será retornado. Se nenhuma correspondência for encontrada para qualquer campo, o Azure Databricks retornará NULL.

Um NULL valor pode ser codificado dentro de um VARIANT, e esse valor não é um SQL NULL. Portanto, parse_json('null') IS NULL é false, mas is_variant_null(parse_json('null')) é true. Um VARIANT nulo codificado pode ser convertido em um SQL NULL convertendo-o para algum tipo. Por exemplo, parse_json('null')::int IS NULL é true.

Exemplos

Os exemplos a seguir usam os dados criados com a instrução em Dados de exemplo.

Nesta secção:

Extrair usando identificador e delimitadores

> SELECT raw:owner, raw:OWNER, raw:['owner'], raw:['OWNER'] FROM store_data;
  amy  amy  amy  NULL

-- Use backticks to escape special characters. References are case insensitive when you use backticks.
-- Use brackets to make them case sensitive.
> SELECT raw:`zip code`, raw:`Zip Code`, raw:['fb:testid'] FROM store_data;
  94025      94025      1234

Extrair campos aninhados

-- Use dot notation
> SELECT raw:store.bicycle FROM store_data;
  '{ "price":19.95, "color":"red" }'

-- Use brackets
> SELECT raw:['store']['bicycle'] FROM store_data;
  '{ "price":19.95, "color":"red" }'

Extrair valores de matrizes

-- Index elements
> SELECT raw:store.fruit[0], raw:store.fruit[1] FROM store_data;
  '{ "weight":8, "type":"apple" }'  '{ "weight":9, "type":"pear" }'

-- Extract subfields from arrays
> SELECT raw:store.book[*].isbn FROM store_data;
  '[ null, "0-553-21311-3", "0-395-19395-8" ]'

-- Access arrays within arrays or structs within arrays
> SELECT raw:store.basket[*],
         raw:store.basket[*][0] first_of_baskets,
         raw:store.basket[0][*] first_basket,
         raw:store.basket[*][*] all_elements_flattened,
         raw:store.basket[0][2].b subfield
  FROM store_data;
  basket                       first_of_baskets   first_basket          all_elements_flattened            subfield
 ---------------------------- ------------------ --------------------- --------------------------------- ----------
  [                            [                  [                     [1,2,{"b":"y","a":"x"},3,4,5,6]   y
    [1,2,{"b":"y","a":"x"}],     1,                 1,
    [3,4],                       3,                 2,
    [5,6]                        5                  {"b":"y","a":"x"}
  ]                            ]                  ]

Comportamento NULL

> SELECT '{"key":null}':key IS NULL sql_null, '{"key":"null"}':key IS NULL;
  true          false

Transmitir valores

-- price is returned as a double, not a string
> SELECT raw:store.bicycle.price::double FROM store_data
  19.95

-- use from_json to cast into more complex types
> SELECT from_json(raw:store.bicycle, 'price double, color string') bicycle FROM store_data
  '{ "price":19.95, "color":"red" }'

-- the column returned is an array of string arrays
> SELECT from_json(raw:store.basket[*], 'array<array<string>>') baskets FROM store_data
  '[
    ["1","2","{\"b\":\"y\",\"a\":\"x\"}]",
    ["3","4"],
    ["5","6"]
  ]'

Expressões VARIANT

-- Using JSON paths for VARIANT
> SELECT raw:store.bicycle FROM store_data_variant;
  '{ "price":19.95, "color":"red" }'

-- Extracting from VARIANT arrays
> SELECT raw:store.fruit[0], raw_variant:store.fruit[1] FROM store_data_variant;
  '{ "weight":8, "type":"apple" }'  '{ "weight":9, "type":"pear" }'

-- SQL NULL behavior of VARIANT NULL values
> SELECT
  parse_json(NULL) IS NULL AS sql_null,
  parse_json('null') IS NULL AS variant_null,
  parse_json('{ "field_a": null }'):field_a IS NULL AS variant_null_value,
  parse_json('{ "field_a": null }'):missing IS NULL AS missing_sql_value_null
  true  false  false  true

-- price is returned as a double, not a VARIANT
> SELECT raw:store.bicycle.price::double FROM store_data_variant
  19.95

Dados de exemplo

> CREATE TABLE store_data AS SELECT
'{
   "store":{
      "fruit": [
        {"weight":8,"type":"apple"},
        {"weight":9,"type":"pear"}
      ],
      "basket":[
        [1,2,{"b":"y","a":"x"}],
        [3,4],
        [5,6]
      ],
      "book":[
        {
          "author":"Nigel Rees",
          "title":"Sayings of the Century",
          "category":"reference",
          "price":8.95
        },
        {
          "author":"Herman Melville",
          "title":"Moby Dick",
          "category":"fiction",
          "price":8.99,
          "isbn":"0-553-21311-3"
        },
        {
          "author":"J. R. R. Tolkien",
          "title":"The Lord of the Rings",
          "category":"fiction",
          "reader":[
            {"age":25,"name":"bob"},
            {"age":26,"name":"jack"}
          ],
          "price":22.99,
          "isbn":"0-395-19395-8"
        }
      ],
      "bicycle":{
        "price":19.95,
        "color":"red"
      }
    },
    "owner":"amy",
    "zip code":"94025",
    "fb:testid":"1234"
 }' as raw

 > CREATE TABLE store_data_variant AS SELECT parse_json(raw) FROM store_data;