JSONPath in action: Correct way to extract data from nested API responses

Real problems encountered ``json { "code": 200, "data": { "user": { "profile": { "name": "Zhang San", "contacts": [ {"type": "email", "value": "zhangsan@example.

Real problems encountered

{
  "code": 200,
  "data": {
    "user": {
      "profile": {
        "name": "张三",
        "contacts": [
          {"type": "email", "value": "[email protected]"},
          {"type": "phone", "value": "13800138000"}
        ]
      }
    },
    "orders": [
      {"id": 1, "amount": 99.99, "status": "paid"},
      {"id": 2, "amount": 199.99, "status": "pending"}
    ]
  }
}
I need to extract:
  • User name
  • All email addresses
  • Paid order amount
Writing multi-layer loops and judgments in code? No, use JSONPath directly.

Correct JSONPath expression

1. Extract user name

$.data.user.profile.name
Result:"张三"

2. Extract all email addresses

$.data.user.profile.contacts[?(@.type=='email')].value
结果:["[email protected]"]

3. Extract the amount of paid orders

$.data.orders[?(@.status=='paid')].amount
结果:[99.99]

4. Extract all order IDs and amounts

$.data.orders[*].[id,amount]
结果:[[1,99.99],[2,199.99]]

Test on Tools Obsession

OpenJSONPath Tester, paste the API response to the left, enter the expression on the right, and click "Test". The tool will immediately display the matching results to help you verify whether the expression is correct.

Common JSONPath Errors

Error 1: Forgot $symbol

❌ data.user.name
✅ $.data.user.name

Error 2: Array index starts at 1

❌ $.data.orders[1]  // 这是第二个元素
✅ $.data.orders[0]  // 这才是第一个元素

Error 3: Filter syntax error

❌ $.data.orders[?(@.status=paid)]    // 单个等号
❌ $.data.orders[?(@.status==paid)]   // 没有引号
✅ $.data.orders[?(@.status=='paid')] // 正确

Error 4: Recursive lookup overused

❌ $..name  // 会找所有层级的 name,可能匹配太多
✅ $.data.user.profile.name  // 明确路径更精确

Error 5: Wrong use of quotes

❌ $.data.orders[?(@.status=="paid")]  // 双引号在某些解析器中会出错
✅ $.data.orders[?(@.status=='paid')]  // 单引号更稳定

Practical Tips

Tip 1: Test the parent path first

Not sure about the data structure? Test the parent path first:
$.data              // 确认能取到 data
$.data.user         // 确认能取到 user
$.data.user.profile // 确认能取到 profile

Tip 2: Use slicing

Only need the first 3 orders?
$.data.orders[0:3]

Tip 3: Get the last element

$.data.orders[-1:]

Tip 4: Multi-field selection

Get multiple fields at the same time:
$.data.orders[*].[id,status]

Tip 5: Complex condition filtering

The amount is greater than 100 and the status is paid:
$.data.orders[?(@.amount>100 && @.status=='paid')]

FAQ

  • Q: What is the difference between JSONPath and JSON?
A: JSON is the data format and JSONPath is the query language. Just like SQL is a database query language, JSONPath is a JSON query language.
  • Q: Do all JSON libraries support JSONPath?
A: No. Supported by Java's JsonPath library, JavaScript's JSONPath-plus library, and Python's jsonpath-ng library. Make sure your library supports it before using it.
  • Q: Why does my expression work in the tool but not in the code?
A: The syntax of different libraries is slightly different. Tool Junkies uses standard JSONPath syntax and recommends using the same library in your code (such as Java's com.jayway.jsonpath).
  • Q: Can JSON data be modified?
A: JSONPath can only be read, not modified. To modify it, it needs to be parsed into an object first, and then serialized after modification.
  • Q: How is the performance?
A: Simple expressions are fast. Complex recursive lookups (such as $..name) can be slow on large JSON. It is recommended to clarify the path.
  • Q: How to deal with null values ​​or missing fields?
A: Use ?() filter:
$.data.orders[?(@.amount)]
Only return orders with amount field.

Full example

API response data (simplified version):
{
  "data": {
    "products": [
      {"id": 1, "name": "iPhone", "price": 999, "inStock": true},
      {"id": 2, "name": "MacBook", "price": 1999, "inStock": false},
      {"id": 3, "name": "iPad", "price": 799, "inStock": true}
    ]
  }
}
Extract all in-stock product names:
$.data.products[?(@.inStock==true)].name
结果:["iPhone","iPad"]
Need to process complex JSON data? Test your expressions in real time on JSONPath Tester for Tool Junkies.