jsonpath for js

/**
         * @license
         * JSONPath 0.8.0 - XPath for JSON
         *
         * Copyright (c) 2007 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}
         */
        function jsonPath(obj, expr, arg) {
            var P = {
                resultType: arg && arg.resultType || ‘VALUE‘,
                result: [],
                normalize: function (expr) {
                    var subX = [];
                    return expr.replace(/[\[‘](\??\(.*?\))[\]‘]/g, function ($0, $1) {
                        return ‘[#‘ + (subX.push($1) - 1) + ‘]‘;
                    }).replace(/‘?\.‘?|\[‘?/g, ‘;‘).replace(/;;;|;;/g, ‘;..;‘).replace(/;$|‘?]|‘$/g, ‘‘).replace(/#([0-9]+)/g, function ($0, $1) {
                        return subX[$1];
                    });
                },
                asPath: function (path) {
                    var x = path.split(‘;‘), p = ‘$‘;
                    for (var i = 1, n = x.length; i < n; i++)
                        p += /^[0-9*]+$/.test(x[i]) ? ‘[‘ + x[i] + ‘]‘ : ‘[\‘‘ + x[i] + ‘\‘]‘;
                    return p;
                },
                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) {
                        var x = 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) {
                                typeof v[m] === ‘object‘ && P.trace(‘..;‘ + x, v[m], p + ‘;‘ + m);
                            });
                        } else if (/,/.test(loc)) {
                            // [name1,name2,...]
                            for (var s = 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(/^\?\((.*?)\)$/, ‘$1‘), v[m], m))
                                    P.trace(m + ‘;‘ + x, v, p);
                            });
                        else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc))
                        // [start:end:step]  phyton slice syntax
                            P.slice(loc, x, val, path);
                    } else
                        P.store(path, val);
                },
                walk: function (loc, expr, val, path, f) {
                    if (val instanceof Array) {
                        for (var i = 0, n = val.length; i < n; i++)
                            if (i in val)
                                f(i, loc, expr, val, path);
                    } else if (typeof val === ‘object‘) {
                        for (var m in val)
                            if (val.hasOwnProperty(m))
                                f(m, loc, expr, val, path);
                    }
                },
                slice: function (loc, expr, val, path) {
                    if (val instanceof Array) {
                        var len = val.length, start = 0, end = len, step = 1;
                        loc.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g, function ($0, $1, $2, $3) {
                            start = parseInt($1 || start);
                            end = parseInt($2 || end);
                            step = parseInt($3 || 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 (var i = 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 new SyntaxError(‘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, ‘$‘);
                return P.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 are 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 two books via subscript union
$..book[:2] The first two 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 that cost 8.95
$..book[?(@.price<30 && @.category=="fiction")] Filter all fiction books cheaper than 30
$..* All members of JSON structure
时间: 2024-10-25 08:02:52

jsonpath for js的相关文章

JsonPath小结

在查看DHC Assertions 模块说明的时候,无意间发现assert模块中JsonBody使用了 JSON Path ,兴趣使然,看了下,发现是类似解析xml用到的 XPath.通过路径来获取json对象的属性值 JSON Path提供了javascript与PHP版本 XPath表达式:/store/book[1]/title JSON Path表达式:.store.book[0].title 或则 x['store']['book'][0]['title'] 同时,官网也有提到,像ja

JsonPath详解

JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is available in many programming languages such as Javascript, Python and PHP. Now also in Java! News 2013-09-27 Released 0.9.0 bug fixes, general i

基于Node.js的强大爬虫 能直接发布抓取的文章哦

基于Node.js的强大爬虫 能直接发布抓取的文章哦 基于Node.js的强大爬虫能直接发布抓取的文章哦!本爬虫源码基于WTFPL协议,感兴趣的小伙伴们可以参考一下 一.环境配置 1)搞一台服务器,什么linux都行,我用的是CentOS 6.5: 2)装个mysql数据库,5.5或5.6均可,图省事可以直接用lnmp或lamp来装,回头还能直接在浏览器看日志: 3)先安个node.js环境,我用的是0.12.7,更靠后的版本没试过: 4)执行npm -g install forever,安装f

python 数据提取之JSON与JsonPATH

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写.同时也方便了机器进行解析和生成.适用于进行数据交互的场景,比如网站前台与后台之间的数据交互. JSON和XML的比较可谓不相上下. Python 2.7中自带了JSON模块,直接import json就可以使用了. 官方文档:http://docs.python.org/library/json.html Json在线解析网站:http://www.json.cn/#

Json与JsonPath

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,因为它良好的可读性与易于机器进行解析和生成等特性,在当前的数据整理和收集中得到了广泛的应用. JSON和XML相比较可谓不相上下. Python 2.X中自带了JSON模块,直接import json就可以使用了. 官方文档:http://docs.python.org/library/json.html Json在线解析网站:http://www.json.cn JSONjson简单来说就是JavaSc

JSONPath - XPath for JSON

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 do

一个js爬虫

1. 第一个demo 2. configs详解——之成员 3. configs详解——之field 4. configs详解——之site, page和console 5. configs详解——之回调函数 6. 爬虫进阶开发——之内置函数 7. 爬虫进阶开发——之模板化 8. 爬虫进阶开发——之图片云托管 9. 爬虫进阶开发——之自动IP代理 10. 爬虫进阶开发——之验证码识别 11. 爬虫进阶开发——之自动JS渲染 12. 爬虫进阶开发——之技巧篇 13. 两个完整demo 14. 开发神

爬虫——json模块与jsonpath模块

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写.同时也方便了机器进行解析和生成.适用于进行数据交互的场景,比如网站前台与后台之间的数据交互. JSON和XML相比较可谓不相上下. Python 3.X中自带了JSON模块,直接import json就可以使用了. 官方文档:http://docs.python.org/library/json.html Json在线解析网站:http://www.json.cn/# J

9.json和jsonpath

数据提取之JSON与JsonPATH JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写.同时也方便了机器进行解析和生成.适用于进行数据交互的场景,比如网站前台与后台之间的数据交互. JSON和XML的比较可谓不相上下. Python 2.7中自带了JSON模块,直接import json就可以使用了. 官方文档:http://docs.python.org/library/json.html Json在线解析网站:ht