Jsonpath for JS

Source: Internet
Author: User
Tags hasownproperty

/** * @license * JSONPath 0.8.0-xpath for JSON * * Copyright (c) Stefan Goessner         (goessner.net) * Licensed under the MIT (mit-license.txt) licence. * * @param {object| Array} obj * @param {String} expr * @param {Object} [arg] * @returns {array|false}*/        functionJsonPath (obj, expr, arg) {varP ={Resulttype:arg&& Arg.resulttype | | ' VALUE ', Result: [], Normalize:function(expr) {varSUBX = []; returnExpr.replace (/[\[') (\?? \ (. *?\)) [\] ']/g,function($ A, $) {                        return' [# ' + (Subx.push ($ 1) + '] '; }). replace (/'? \. '? | \['?/g, '; '). Replace (/;;;|;;/ g, ';..; '). Replace (/;$| '?]| ') $/g, "). Replace (/# ([0-9]+)/g,function($ A, $) {                        returnSubx[$1];                }); }, Aspath:function(path) {varx = Path.split (';'), p = ' $ ';  for(vari = 1, n = x.length; I < n; i++) P+ =/^[0-9*]+$/.test (X[i])? ' [' + x[i] + '] ': ' [\ ' + x[i] + ' \ '] '; returnp; }, Store:function(P, v) {if(P) p.result[p.result.length]= P.resulttype = = = ' PATH '?P.aspath (P): v; return!!p; }, Trace:function(expr, Val, path) {if(expr) {varx = Expr.split (';'), loc =X.shift (); X= X.join ('; ')); if(Val &&val.hasownproperty (Loc)) P.trace (x, Val[loc], path+ '; ' +Loc); Else if(loc = = = ' * ')) P.walk (Loc, X, Val, Path,function(M, l, X, V, p) {P.trace (M+ '; ' +x, V, p);                        }); Else if(loc = = = ' ... ')) {p.trace (x, Val, path); P.walk (Loc, X, Val, Path,function(M, l, X, V, p) {typeofV[m] = = = ' object ' && p.trace (' ...; ' + x, V[m], P + '; ' +m);                        }); } Else if(/,/. Test (Loc)) {                            //[name1,name2,...]                             for(vars = loc.split (/'?, '?/), I = 0, n = s.length; I < n; i++) P.trace (S[i]+ '; ' +x, Val, path); } Else if(/^\(.*?\)$/. Test (Loc))//[(expr)]P.trace (P.eval (Loc, Val, path.substr (path.lastindexof (';') + 1)) + '; ' +x, Val, path); Else if(/^\?\(.*?\)$/. Test (Loc))// [?( Expr)]P.walk (Loc, X, Val, Path,function(M, l, X, V, p) {if(P.eval (L.replace) (/^\?\ (. *?) \) $/, ' $ '), V[m], M)) P.trace (M+ '; ' +x, V, p);                        }); Else if(/^(-? [0-9]*):(-? [0-9]*):? ([0-9]*) $/. Test (Loc))//[start:end:step] Phyton slice syntaxp.slice (Loc, X, Val, path); } ElseP.store (Path, Val); }, walk:function(Loc, expr, Val, path, f) {if(ValinstanceofArray) {                         for(vari = 0, n = val.length; I < n; i++)                            if(IinchVal) F (i, Loc, expr, Val, path); } Else if(typeofval = = = ' object ') {                         for(varMinchval)if(Val.hasownproperty (M)) F (M, loc, expr, Val, path); }}, Slice:function(Loc, expr, Val, path) {if(ValinstanceofArray) {                        varLen = val.length, start = 0, end = len, step = 1; Loc.replace (/^(-? [0-9]*):(-? [0-9]*):? (-? [0-9]*] $/g,function($ A, $ $, $) {Start= parseint ($ | |start); End= parseint ($ | |end); Step= parseint ($ | |step);                        }); Start= Start < 0? Math.max (0, start +len): Math.min (len, start); End= End < 0? Math.max (0, End +len): Math.min (len, end);  for(vari = start; I < end; i + =Step) P.trace (i+ '; ' +expr, Val, path); }}, Eval:function(x, _v) {Try {                        return$ && _v && eval (x.replace (/@/g, ' _v ')); } Catch(e) {Throw NewSyntaxError (' JsonPath: ' + e.message + ': ' + x.replace (/@/g, ' _v '). Replace (/\^/g, ' _a ')));            }                }            }; var$ =obj; if(Expr && obj && (p.resulttype = = ' VALUE ' | | P.resulttype = = ' PATH ') {p.trace (p.normalize (expr). Replace (/^\$;/, '), obj, ' $ '); returnP.result.length? P.result:false; }        }

JSONPath Description
$ The root object/element
@ The current object/element
. Child Member operator
.. Recursive descendant operator; JSONPath borrows this syntax from e4x
* Wildcard matching all objects/elements regardless their names
[] Subscript operator
[,] Union operator for alternate names or array indices as a set
[start:end:step] Array slice operator borrowed from Es4/python
?() Applies a filter (script) expression via static evaluation
() Script expression via static evaluation

Given This sample data set, see Example expressions below:

{  "Store": {    "Book": [       {        "category": "Reference",        "Author": "Nigel Rees",        "title": "Sayings of the Century",        "Price": 8.95      }, {        "Category": "Fiction",        "Author": "Evelyn Waugh",        "title": "Sword of Honour",        "Price": 12.99      }, {        "Category": "Fiction",        "Author": "Herman Melville",        "title": "Moby Dick",        "ISBN": "0-553-21311-3",        "Price": 8.99      }, {         "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 JSONPath Expressions:

JSONPath Description
$.store.book[*].author The authors of all books in the store
$..author All authors
$.store.* All things in store, which is some books and a red bicycle
$.store..price The price of everything in the store
$..book[2] The third book
$..book[(@.length-1)] The last book via script subscript
$..book[-1:] The last book via Slice
$..book[0,1] The first and the books via subscript union
$..book[:2] The first and the books via subscript array slice
$..book[?(@.isbn)] Filter All books with ISBN number
$..book[?(@.price<10)] Filter all books cheaper than 10
$..book[?(@.price==8.95)] Filter All Books 8.95
$..book[?(@.price<30 && @.category=="fiction")] Filter all fiction books cheaper than 30
$..* All members of JSON structure

Jsonpath for JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.