What's the correct JsonPath expression to sear

2019-06-24 07:42发布

问题:

Most examples deal with the book store example from Stefan Gössner, however I'm struggling to define the correct JsonPath expression for a simple object (no array):

{ "Id": 1, "Name": "Test" }

To check if this json contains Id = 1.

I tried the following expression: $..?[(@.Id == 1]), but this does find any matches using Json.NET?

Also tried Manatee.Json for parsing, and there it seems the jsonpath expression could be like $[?($.Id == 1)] ?

回答1:

The path that you posted is not valid. I think you meant $..[?(@.Id == 1)] (some characters were out of order). My answer assumes this.

The JSON Path that you're using indicates that the item you're looking for should be in an array.

$                      start
 ..                    recursive search (1)
   [                   array item specification
    ?(                 item-based query
      @.Id == 1        where the item is an object with an "Id" with value == 1 at the root
               )       end item-based query
                ]      end array item specification

(1) the conditions following this could match a value no matter how deep in the hierarchy it exists

You want to just navigate the object directly. Using $.Id will return 1, which you can validate in your application.

All of that said...

It sounds to me like you want to validate that the Id property is 1 rather than to search an array for an object where the Id property is 1. To do this, you want JSON Schema, not JSON Path.

JSON Path is a query language for searching for values which meet certain conditions (e.g. an object where Id == 1.

JSON Schema is for validating that the JSON meet certain requirements (your data's in the right shape). A JSON Schema to validate that your object has a value of 1 could be something like

{
  "properties": {
    "Id": {"const":1}
  }
}

Granted this isn't very useful because it'll only validate that the Id property is 1, which ideally should only be true for one object.