{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } Example paths:
Expression Result $ Matches the root document (a single value) $..* Matches all members in the document (lots of values) $.store.book[*].author The authors of all books in the store $..author All authors $.store.* All things in store (2 books and a bicycle) $.store..price The price of everything in the store $..book[2] The third book $..book[-1:] The last book in order $..book[:2] The first two books JSONPath in Delphi The JSONPath API is short and simple. It consists of a TJsonPath record with only a couple of methods.
For one-off matching, use the static Match method:
var Doc: IJsonDocument; Matches: TArray<TJsonValue>; begin Doc := TJsonDocument.Load(...); Matches := TJsonPath.Match(Doc, '$.store.book[*].author'); end; If you plan to use the same path on multiple (sub)documents, then it is faster to parse the path once, and then apply it multiple times:
var Doc1, Doc2: IJsonDocument; Path: TJsonPath; Matches1, Matches2: TArray<TJsonValue>; begin Doc1 := TJsonDocument.Load(...); Doc2 := TJsonDocument.Load(...);
Matches1 := Path.Match(Doc1); Matches2 := Path.Match(Doc2); end; You can also run the path on sub-trees:
var Doc: IJsonDocument; Store: TJsonValue; Matches: TArray<TJsonValue>; begin Doc := TJsonDocument.Load(...); Store := Doc.Root.Values['store']; Matches := TJsonPath.Match(Store, '$.book[*].author'); end; If you are only interested in a single (or the first) match, then you can use MatchSingle instead:
var Doc: IJsonDocument; Match: TJsonValue; begin Doc := TJsonDocument.Load(...); if (TJsonPath.MatchSingle(Store, '$.book[*]', Match)) then ... end;
----------------------------------------------
Delphi4Linux Delphi三层/FireDAC 技术群:734515869 http://www.cnblogs.com/rtcmw