How to use json path for json manipulations

November 29, 2022

What is JsonPath

Initially created by Stefan Goessner is an adaptation of XPATH but for JSON.

with JSON path:

  • search if specific value exists in JSON
  • transform JSON to a shape you need
  • reduce JSON size for readability or payload reduction

Tutorial

Let's say this is input JSON

{
  "firstName": "Charles",
  "lastName": "Doe",
  "age": 41,
  "location": {
    "city": "San Fracisco",
    "postalCode": "94103"
  },
  "hobbies": [
    "chess",
    "netflix"
  ]
}

1. start expression with $ always

json path

$.

output:

[
  {
    "firstName": "Charles",
    "lastName": "Doe",
    "age": 41,
    "location": {
      "city": "San Fracisco",
      "postalCode": "94103"
    },
    "hobbies": [
      "chess",
      "netflix"
    ]
  }
]

try start expression in a playground

2. access simple attribute

json path

$.firstName

output:

[
  "Charles"
]

try simple attribute select in a playground

3. access array element

json path

$.hobbies[0]

output:

[
  "chess"
]

try array selection in a playground

4. wildcard - get all values regardless of a name

json path

$.location.*

output (notice only values are included without keys)

[
  "San Fracisco",
  "94103"
]

try wildcard in a playground