← Torna al Blog

Trovare percorsi JSON: JSONPath e navigazione dati

Guida completa a JSONPath per navigare e query dati JSON: sintassi, esempi pratici, strumenti online e librerie. Impara a trovare percorsi in strutture JSON complesse.

Big JSON Team13 min di letturatools
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

13 min di lettura

# Trovare percorsi JSON: JSONPath e navigazione dati

Navigare strutture JSON complesse può essere difficile. JSONPath è un linguaggio di query che rende semplice trovare e estrarre dati da JSON. Questa guida ti insegnerà tutto su JSONPath e come usarlo efficacemente.

Cos'è JSONPath?

JSONPath è per JSON quello che XPath è per XML:

  • Linguaggio di query per navigare JSON
  • Sintassi semplice per path complessi
  • Filtri potenti per selezionare dati
  • Standard de facto supportato da molte librerie

Esempio base

JSON:
{

"negozio": {

"libri": [

{ "titolo": "Il Nome della Rosa", "prezzo": 15.99 },

{ "titolo": "1984", "prezzo": 12.99 }

]

}

}

JSONPath:
$.negozio.libri[0].titolo

// Risultato: "Il Nome della Rosa"

Sintassi JSONPath

Simboli base

| Simbolo | Descrizione | Esempio |

|---------|-------------|---------|

| $ | Root | $ |

| @ | Nodo corrente | @.prezzo |

| . | Child | $.negozio.libri |

| .. | Recursive descent | $..prezzo |

| | Wildcard | $.negozio. |

| [] | Array index | $[0], $[0,1] |

| [start:end] | Array slice | $[0:5] |

| ?() | Filtro | $[?(@.prezzo < 15)] |

Accesso proprietà

Dot notation:
$.utente.nome

$.utente.indirizzo.città

Bracket notation:
$['utente']['nome']

$['utente']['indirizzo']['città']

Con spazi o caratteri speciali:
$['nome utente']

$['email-address']

$['data-nascita']

Array

Indice specifico:
$.libri[0]        // Primo elemento

$.libri[2] // Terzo elemento

$.libri[-1] // Ultimo elemento

Multipli indici:
$.libri[0,2,4]    // Elementi 0, 2 e 4
Slice:
$.libri[0:3]      // Primi 3 elementi (0,1,2)

$.libri[2:5] // Elementi da 2 a 4

$.libri[::2] // Ogni 2 elementi

$.libri[-3:] // Ultimi 3 elementi

Wildcard

Tutti i children:
$.negozio.       // Tutti i child di negozio

$.libri[] // Tutti gli elementi array

$.libri[].titolo // Tutti i titoli

Recursive descent (..)

Trova ovunque:
$..prezzo         // Tutti i campi "prezzo" ovunque

$..libri[].autore // Tutti gli autori ovunque

Filtri

Sintassi filtro

$[?(@.condizione)]

Operatori di confronto

// Uguale

$[?(@.prezzo == 15.99)]

// Diverso

$[?(@.disponibile != false)]

// Maggiore

$[?(@.prezzo > 10)]

// Minore

$[?(@.quantità < 5)]

// Maggiore o uguale

$[?(@.età >= 18)]

// Minore o uguale

$[?(@.prezzo <= 20)]

Operatori logici

AND (&&):
$[?(@.prezzo < 20 && @.disponibile == true)]
OR (||):
$[?(@.categoria == 'romanzo' || @.categoria == 'giallo')]
NOT (!):
$[?(!@.eliminato)]

Filtri complessi

// Libri economici e disponibili

$.libri[?(@.prezzo < 15 && @.disponibile)]

// Utenti adulti attivi

$.utenti[?(@.età >= 18 && @.attivo == true)]

// Prodotti in sconto

$.prodotti[?(@.prezzo_originale > @.prezzo_scontato)]

Esempi pratici

E-commerce

JSON:
{

"negozio": {

"nome": "TechStore",

"prodotti": [

{

"id": 1,

"nome": "Laptop",

"prezzo": 999,

"categoria": "elettronica",

"disponibile": true,

"tag": ["computer", "portatile"]

},

{

"id": 2,

"nome": "Mouse",

"prezzo": 29,

"categoria": "elettronica",

"disponibile": true,

"tag": ["accessori"]

},

{

"id": 3,

"nome": "Scrivania",

"prezzo": 199,

"categoria": "arredamento",

"disponibile": false,

"tag": ["ufficio"]

}

]

}

}

Query: 1. Tutti i prodotti:
$.negozio.prodotti[]
2. Prodotti disponibili:
$.negozio.prodotti[?(@.disponibile == true)]

// Risultato: Laptop, Mouse

3. Prodotti sotto €100:
$.negozio.prodotti[?(@.prezzo < 100)]

// Risultato: Mouse

4. Prodotti elettronica disponibili:
$.negozio.prodotti[?(@.categoria == 'elettronica' && @.disponibile)]

// Risultato: Laptop, Mouse

5. Tutti i prezzi:
$.negozio.prodotti[].prezzo

// Risultato: [999, 29, 199]

6. Tutti i tag:
$..tag[]

// Risultato: ["computer", "portatile", "accessori", "ufficio"]

API Social Media

JSON:
{

"utenti": [

{

"id": 1,

"nome": "Marco",

"post": [

{ "id": 101, "testo": "Ciao!", "likes": 5 },

{ "id": 102, "testo": "JSON è fantastico", "likes": 15 }

]

},

{

"id": 2,

"nome": "Laura",

"post": [

{ "id": 201, "testo": "Buongiorno", "likes": 8 },

{ "id": 202, "testo": "Weekend!", "likes": 20 }

]

}

]

}

Query: 1. Post con >10 likes:
$..post[?(@.likes > 10)]

// Risultato: post 102, 202

2. Tutti i like totali:
$..post[].likes

// Risultato: [5, 15, 8, 20]

3. Post di Marco:
$.utenti[?(@.nome == 'Marco')].post[]

Librerie JSONPath

JavaScript - jsonpath

const jp = require('jsonpath');

const data = {

negozio: {

prodotti: [

{ nome: "Laptop", prezzo: 999 },

{ nome: "Mouse", prezzo: 29 }

]

}

};

// Query

const risultato = jp.query(data, '$.negozio.prodotti[?(@.prezzo < 100)]');

console.log(risultato);

// [{ nome: "Mouse", prezzo: 29 }]

// Trova path

const paths = jp.paths(data, '$..prezzo');

console.log(paths);

// [['negozio', 'prodotti', 0, 'prezzo'], ['negozio', 'prodotti', 1, 'prezzo']]

// Ottieni valori

const valori = jp.value(data, '$.negozio.prodotti[0].nome');

console.log(valori);

// "Laptop"

Python - jsonpath-ng

from jsonpath_ng import jsonpath, parse

data = {

"negozio": {

"prodotti": [

{"nome": "Laptop", "prezzo": 999},

{"nome": "Mouse", "prezzo": 29}

]

}

}

# Parse espressione

expr = parse('$.negozio.prodotti[].nome')

# Trova matches

matches = [match.value for match in expr.find(data)]

print(matches)

# ['Laptop', 'Mouse']

# Con filtro (usa jsonpath-rw-ext)

from jsonpath_rw_ext import parse

expr = parse('$.negozio.prodotti[?(@.prezzo < 100)]')

cheap = [match.value for match in expr.find(data)]

print(cheap)

# [{'nome': 'Mouse', 'prezzo': 29}]

Strumenti online

JSON Simplify

Funzionalità:
  • Tree viewer con path automatico
  • Click per copiare path
  • Ricerca interattiva
  • Evidenziazione path

Uso:
  • Carica JSON in jsonsimplify.com
  • Click su qualsiasi nodo
  • Path mostrato automaticamente
  • Copia con un click
  • JSONPath Online Evaluator

    URL: jsonpath.com Funzionalità:
    • Testa espressioni JSONPath
    • Esempi integrati
    • Syntax highlighting
    • Risultati in tempo reale

    Uso:
  • Incolla JSON
  • Scrivi espressione JSONPath
  • Vedi risultati istantanei
  • Casi d'uso avanzati

    1. Estrazione dati API

    // Response API GitHub
    

    const response = {

    items: [

    {

    name: "react",

    owner: { login: "facebook" },

    stargazers_count: 200000

    },

    {

    name: "vue",

    owner: { login: "vuejs" },

    stargazers_count: 180000

    }

    ]

    };

    // Repos con >190k stars

    const popular = jp.query(response,

    '$.items[?(@.stargazers_count > 190000)].name'

    );

    // ["react"]

    2. Validazione dati

    function validateRequired(data, paths) {
    

    for (const path of paths) {

    const result = jp.query(data, path);

    if (result.length === 0) {

    throw new Error(Campo richiesto mancante: ${path});

    }

    }

    }

    // Verifica campi obbligatori

    validateRequired(userData, [

    '$.nome',

    '$.email',

    '$.indirizzo.città'

    ]);

    3. Trasformazione dati

    const ordini = {
    

    ordini: [

    { id: 1, totale: 100, stato: "completato" },

    { id: 2, totale: 200, stato: "in_attesa" },

    { id: 3, totale: 150, stato: "completato" }

    ]

    };

    // Calcola totale ordini completati

    const completati = jp.query(ordini,

    '$.ordini[?(@.stato == "completato")].totale'

    );

    const somma = completati.reduce((a, b) => a + b, 0);

    console.log(Totale: €${somma});

    // Totale: €250

    Best practices

    1. Preferisci path specifici a ..

    // ✅ Veloce e preciso
    

    $.negozio.prodotti[].prezzo

    // ❌ Lento su JSON grandi

    $..prezzo

    2. Usa filtri per performance

    // ✅ Filtra poi accedi
    

    $.utenti[?(@.attivo)].email

    // ❌ Accedi tutto poi filtra

    $.utenti[].email // poi filtra in JS

    3. Valida path prima dell'uso

    function safeQuery(data, path) {
    

    try {

    return jp.query(data, path);

    } catch (error) {

    console.error('Path non valido:', path);

    return [];

    }

    }

    4. Cache path complessi

    // Compila path una volta
    

    const complexPath = jp.compile('$.prodotti[?(@.prezzo > 100 && @.disponibile)]');

    // Riusa

    const result1 = complexPath.query(data1);

    const result2 = complexPath.query(data2);

    Conclusione

    JSONPath è essenziale per:

    • ✅ Navigare JSON complessi
    • ✅ Estrarre dati specifici
    • ✅ Filtrare array
    • ✅ Validare strutture
    • ✅ Trasformare dati

    Strumenti consigliati:
    • Online: JSON Simplify, jsonpath.com
    • JavaScript: jsonpath library
    • Python: jsonpath-ng

    Padroneggia JSONPath per lavorare efficacemente con dati JSON complessi!

    Share:

    Articoli Correlati

    Read in English