Jsonpath-xpath for JSON

Source: Internet
Author: User
Tags php example xml example xpath

http://goessner.net/articles/JsonPath/

[ edit] [ comment] [remove] |  2007-02-21| E1 # Jsonpath-xpath for JSON

A frequently emphasized advantage of XML is the availability of plenty tools to analyse, transform and selectively extract Data out of XML Documents. XPath is one of these powerful tools.

It's time to wonder, if there was a need for something like Xpath4json and what's the problems it can Solve.

    • Data May is interactively found and extracted out of JSON structures on the client without special Scripting.
    • JSON data requested by the client can is reduced to the relevant parts on the server, such minimizing the bandwidth usage of the server Response.

If We agree, that's a tool for picking parts out of a JSON structure at hand does make sense, some questions come up. How should it does its job? How does JSONPath expressions look like?

Due to the fact, which JSON is a natural representation of data for the C family of programming languages, the chances is high, that the particular language have native syntax elements to access a JSON structure.

The following XPath expression

/store/book[1]/title

Would look like

x.store.book[0].title

Or

x[‘store‘][‘book‘][0][‘title‘]

In Javascript, Python and PHP with a variable x holding the JSON structure. Here we observe, that the particular language usually have a fundamental XPath feature already built IN.

The JSONPath tool in question should ...

    • Be naturally based on those language characteristics.
    • Cover only essential parts of XPath 1.0.
    • Be lightweight in code size and memory Consumption.
    • Be Runtime Efficient.
[ edit] [ comment] [remove] |  2007-08-17| E2 # JSONPath expressions

JSONPath expressions refer to a JSON structure in the same as XPath expression is used in combination with an XML Document. Since a JSON structure is usually anonymous and doesn ' t necessarily has a "ROOT member object" JSONPath assumes the ABSTR Act name $ assigned to the outer level Object.

JSONPath expressions can use the dot–notation

$.store.book[0].title

or the bracket–notation

$[‘store‘][‘book‘][0][‘title‘]

For input Pathes. Internal or output pathes'll always be converted to the more general bracket–notation.

JSONPath allows the wildcard symbol * for member names and array Indices. It borrows the descendant operator ' ... ' from e4x and the array slice syntax proposal from [start:end:step] ECMASCRI PT 4.

Expressions of the underlying scripting language (<expr>) can be used as a alternative to explicit names or indices as in

$.store.book[(@.length-1)].title

Using the symbol ' @ ' for the current Object. Filter expressions is supported via the syntax as in ?(<boolean expr>)

$.store.book[?(@.price < 10)].title

Here are a complete overview and a side by side comparison of the JSONPath syntax elements with its XPath counterparts.

Xpath JSONPath Description
/ $ The root object/element
. @ The current object/element
/ . or [] Child operator
.. n/a Parent operator
// .. Recursive Descent. JSONPath borrows this syntax from E4x.
* * Wildcard. All objects/elements regardless their names.
@ n/a Attribute Access. JSON structures don ' t has Attributes.
[] [] Subscript Operator. XPath uses it to iterate over element collections and for Predicates. In Javascript and JSON it is the native array Operator.
| [,] Union operator in XPath results in a combination of node Sets. JSONPath allows alternate names or array indices as a set.
n/a [start:end:step] Array slice operator borrowed from ES4.
[] ? () Applies a filter (script) Expression.
n/a () Script expression, using the underlying script Engine.
() n/a Grouping in Xpath

The XPath have a lot more to offer (location pathes in not abbreviated syntax, operators and FUNCTIONS) than listed Here. Moreover there is a remarkable difference how the subscript operator works in Xpath and JSONPath.

    • Square brackets in XPath expressions all operate on the node set resulting from the previous path Fragment. Indices always start by 1.
    • With JSONPath square brackets operate on the object or an array addressed by the previous path Fragment. Indices always start by 0.
[ edit] [ comment] [remove] |  2007-08-18| E3 # JSONPath examples

Let's practice JSONPath expressions by some more examples. We start with a simple JSON structure built through an XML example representing a bookstore (original XML file).

{"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": " title ": " Moby Dick ", " ISBN ": " price ": 8.99}, {" category ": " Fiction ",  "author":  "title":  "the Lord of The Rings ", " ISBN ": " 0-395-19395-8 ", " price ": 22.99}],  "bicycle": { "color":  "red",  "price": 19.95}}  
Xpath JSONPath Result
/store/book/author $.store.book[*].author The authors of all books in the store
//author $..author All authors
/store/* $.store.* All things in store, which is some books and a red Bicycle.
/store//price $.store..price The price of everything in the Store.
//book[3] $..book[2] The third book
//book[last()] $..book[(@.length-1)]
$..book[-1:]
The last book is in Order.
//book[position()<3] $..book[0,1]
$..book[:2]
The first and the books
//book[isbn] $..book[?(@.isbn)] Filter All books with ISBN number
//book[price<10] $..book[?(@.price<10)] Filter all books Cheapier than 10
//* $..* All Elements in XML Document. All members of the JSON Structure.
[ edit] [ comment] [remove] |  2007-08-22| e4 # JSONPath Implementation

JSONPath is implemented-in Javascript for clientside usage and Ported-to-PHP for use on the Server.

Usage

All downloading either of the files need

    • Jsonpath.js
    • jsonpath.php

Include it in your program and use the simple API consisting of one single Function.

jsonPath(obj, expr [, args])

Parameters

obj (object|array):
Object representing the JSON structure.
expr (string):
JSONPath expression String.
args (object|undefined):
Object controlling path Evaluation and OUTPUT. Currently only one member is Supported.
args.resultType ("VALUE"|"PATH"):
causes the result to be either matching values (default) or normalized path expressions.

Return value:

(array|false):
Array holding either values or normalized path expressions matching the input path expression, which can be used fo  R Lazy Evaluation. In case of false no Match.

Javascript Example:

/*...*/},  ' Store ' JSON object from above    ' $. Author "). tojsonstring (),    " $.. Author ", {resulttype:" PATH "}). tojsonstring ();   

PHP Example:

We need here to convert the JSON string to a PHP array First. I am using Michal Migurski ' s JSON parser for.

Require_once (' json.php ');      //JSON parserrequire_once (' jsonpath.php ');  ' {...} ';  "$.. Author ", Array (" PATH ")), $res 1 = $parser->encode ($match 1), $res 2 = $parser->encode ($match 2);   

Results

Both Javascript and PHP example result in the following JSON arrays (as strings):

"Nigel Rees",  "Evelyn Waugh",  "Herman Melville",  "$[' store ' [' book '][0][' author ']",  "$[' Store ' [' book '][3][' author ']"   

Please note, then the return value jsonPath of is an array, which is also a valid JSON Structure. So-might want to apply to the jsonPath resulting structure again or use one of the your favorite array methods as sort wit H it.

[ edit] [ comment] [remove] |  2007-08-24| e5 # issues
    • Currently only a single quotes allowed inside of JSONPath expressions.
    • Script expressions inside of JSONPath locations is currently not recursively evaluated by jsonPath . Only the global and $ local @ symbols is expanded by a simple regular expression.
    • An alternative-to-return in case of jsonPath false no match is to return a empty array in the Future.

Jsonpath-xpath for JSON

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.