Condividi tramite


JSON_QUERY (Transact-SQL)

Si applica a: SQL Server 2016 (13.x) e versioni successive di Istanza gestita di SQL diAzure Istanza gestita di SQL diAzure Azure Synapse Analyticsin Microsoft FabricWarehouse nel database SQL diMicrosoft Fabricin Microsoft Fabric

La JSON_QUERY sintassi estrae un oggetto o una matrice da una stringa JSON.

Per estrarre un valore scalare da una stringa JSON anziché da un oggetto o da una matrice, vedere JSON_VALUE. Per informazioni sulle differenze tra JSON_VALUE e JSON_QUERY, vedi Confrontare JSON_VALUE e JSON_QUERY.

Convenzioni relative alla sintassi Transact-SQL

Syntax

JSON_QUERY ( expression [ , path ] [ WITH ARRAY WRAPPER ] )

Arguments

expression

Espressione. In genere il nome di una variabile o di una colonna che contiene testo JSON.

Se JSON_QUERY trova JSON non valido nell'espressione prima di trovare il valore identificato dal percorso, la funzione restituisce un errore. Se JSON_QUERY non trova il valore identificato dal percorso, analizza l'intero testo e restituisce un errore se trova JSON non valido in qualsiasi punto dell'espressione.

path

Percorso JSON che specifica l'oggetto o la matrice da estrarre.

In SQL Server 2017 (14.x) e nel database SQL di Azure è possibile specificare una variabile come valore di path.

Il percorso JSON può specificare la modalità lax o strict per l'analisi. Se non si specifica la modalità di analisi, la modalità predefinita è lax. Per altre informazioni, vedere Espressioni di percorso JSON nel motore di database SQL.

Il valore predefinito per path è $. Di conseguenza, se non si specifica un valore per path, JSON_QUERY restituisce l'espressione di input.

Se il formato del percorso non è valido, JSON_QUERY restituisce un errore.

CON AVVOLGIMENTO ARRAY

Note

WITH ARRAY WRAPPER attualmente è in anteprima ed è disponibile solo in SQL Server 2025 (17.x).

La funzione SQL JSON_QUERY ANSI viene attualmente usata per restituire un oggetto JSON o una matrice in un percorso specificato. Con il supporto per i jolly degli array in SQL/JSON path expression, introdotto in SQL Server 2025 (17.x), JSON_QUERY può essere utilizzato per restituire proprietà specifiche degli elementi in un array JSON dove ogni elemento è un oggetto JSON. Poiché le ricerche con caratteri jolly possono restituire più valori, specificare la WITH ARRAY WRAPPER clausola in un'espressione di query JSON insieme a un'espressione di percorso SQL/JSON con caratteri jolly o intervallo o elenco per restituire i valori come matrice JSON. WITH ARRAY WRAPPER la clausola è supportata solo se l'input è un tipo json .

Si consideri il documento JSON seguente:

DECLARE @j AS JSON = '{
    "id": 2,
    "first_name": "Mamie",
    "last_name": "Baudassi",
    "email": "mbaudassi1@example.com",
    "gender": "Female",
    "ip_address": "148.199.129.123",
    "credit_cards": [
        {
            "type": "jcb",
            "card#": "3545138777072343",
            "currency": "Koruna"
        },
        {
            "type": "diners-club-carte-blanche",
            "card#": "30282304348533",
            "currency": "Dong"
        },
        {
            "type": "jcb",
            "card#": "3585303288595361",
            "currency": "Yuan Renminbi"
        },
        {
            "type": "maestro",
            "card#": "675984450768756054",
            "currency": "Rupiah"
        },
        {
            "type": "instapayment",
            "card#": "6397068371771473",
            "currency": "Euro"
        }
    ]
}';

Il percorso $.credit_cards punta a una matrice JSON in cui ogni elemento è un oggetto JSON valido. Ora, la JSON_QUERY funzione può essere usata con il supporto dei caratteri jolly della matrice per restituire tutti o specifici valori della type proprietà, ad esempio:

SELECT JSON_QUERY(@j, '$.credit_cards[*].type' WITH ARRAY WRAPPER);

La tabella seguente illustra vari esempi di espressione di percorso SQL/JSON con caratteri jolly e il valore restituito usando JSON_QUERY WITH ARRAY WRAPPER.

Path Valore restituito
$.credit_cards[0].type ["jcb"]
$.credit_cards[*].type ["jcb","diners-club-carte-blanche","jcb","maestro","instapayment"]
$.credit_cards[0, 2].type ["jcb","jcb"]
$.credit_cards[1 to 3].type ["diners-club-carte-blanche","jcb","maestro"]
$.credit_cards[last].type ["instapayment"]
$.credit_cards[last, 0].type ["instapayment","jcb"]
$.credit_cards[last, last].type ["instapayment","instapayment"]
$.credit_cards[ 0, 2, 4].type ["jcb","jcb","instapayment"]

Valore restituito

Restituisce un frammento JSON di tipo nvarchar(max). Le regole di confronto del valore restituito sono le stesse di quelle dell'espressione di input.

Se il valore non è un oggetto o una matrice:

  • In modalità lax, JSON_QUERY restituisce null.

  • In modalità strict, JSON_QUERY restituisce un errore.

Remarks

Modalità lax e modalità strict

Si consideri il testo JSON seguente:

{
   "info": {
      "type": 1,
      "address": {
         "town": "Cheltenham",
         "county": "Gloucestershire",
         "country": "England"
      },
      "tags": ["Sport", "Water polo"]
   },
   "type": "Basic"
}

Nella tabella seguente viene confrontato il comportamento di JSON_QUERY in modalità lax e in modalità strict. Per altre informazioni sulla specifica facoltativa della modalità percorso (lax o strict), vedere Espressioni di percorso JSON nel motore di database SQL.

Path Valore restituito in modalità lax Valore restituito in modalità strict Altre informazioni
$ Restituisce l'intero testo JSON. Restituisce l'intero testo JSON.
$.info.type NULL Error Non è un oggetto o una matrice.

Utilizzare invece JSON_VALUE.
$.info.address.town NULL Error Non è un oggetto o una matrice.

Utilizzare invece JSON_VALUE.
$.info."address" N'{ "town":"Cheltenham", "county":"Gloucestershire", "country":"England" }' N'{ "town":"Cheltenham", "county":"Gloucestershire", "country":"England" }'
$.info.tags N'[ "Sport", "Water polo"]' N'[ "Sport", "Water polo"]'
$.info.type[0] NULL Error Non è una matrice.
$.info.none NULL Error La proprietà non esiste.

Uso di JSON_QUERY con FOR JSON

JSON_QUERY restituisce un frammento JSON valido. Di conseguenza, FOR JSON non esegue l'escape dei caratteri speciali nel valore restituito JSON_QUERY.

Se si restituiscono risultati con FOR JSON e si includono dati già in formato JSON (in una colonna o come risultato di un'espressione), eseguire il wrapping dei dati JSON con JSON_QUERY senza il parametro path .

Examples

A. Restituire un frammento JSON

Nell'esempio seguente viene illustrato come restituire un frammento JSON da una colonna CustomFields nei risultati della query.

SELECT PersonID,
       FullName,
       JSON_QUERY(CustomFields, '$.OtherLanguages') AS Languages
FROM Application.People;

B. Includere frammenti JSON nell'output FOR JSON

Nell'esempio seguente viene illustrato come includere frammenti JSON nell'output della clausola FOR JSON.

SELECT StockItemID,
       StockItemName,
       JSON_QUERY(Tags) AS Tags,
       JSON_QUERY(CONCAT('["', ValidFrom, '","', ValidTo, '"]')) AS ValidityPeriod
FROM Warehouse.StockItems
FOR JSON PATH;

C. Usare WITH ARRAY WRAPPER con JSON_QUERY funzione

L'esempio seguente illustra l'uso di WITH ARRAY WRAPPER con la JSON_QUERY funzione per restituire più elementi da una matrice JSON:

DECLARE @j JSON = '
{"id":2, "first_name":"Mamie", "last_name":"Baudassi", "email":"mbaudassi1@example.com", "gender":"Female", "ip_address":"148.199.129.123", "credit_cards":[ {"type":"jcb", "card#":"3545138777072343", "currency":"Koruna"}, {"type":"diners-club-carte-blanche", "card#":"30282304348533", "currency":"Dong"}, {"type":"jcb", "card#":"3585303288595361", "currency":"Yuan Renminbi"}, {"type":"maestro", "card#":"675984450768756054", "currency":"Rupiah"}, {"type":"instapayment", "card#":"6397068371771473", "currency":"Euro"}]}
';
SELECT JSON_QUERY(@j, '$.credit_cards[*].type' WITH ARRAY WRAPPER ) as credit_card_types;

Il set di risultati è il seguente.

credit_card_types
--------
["jcb","diners-club-carte-blanche","jcb","maestro","instapayment"]