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 |
jsonpath for js的更多相关文章
- jsonpath
1. java 类库 jayway/JsonPath maven 使用方法 <dependency> <groupId>com.jayway.jsonpath</grou ...
- JsonPath详解
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPat ...
- 基于Node.js的强大爬虫 能直接发布抓取的文章哦
基于Node.js的强大爬虫 能直接发布抓取的文章哦 基于Node.js的强大爬虫能直接发布抓取的文章哦!本爬虫源码基于WTFPL协议,感兴趣的小伙伴们可以参考一下 一.环境配置 1)搞一台服务器,什 ...
- 一个js爬虫
1. 第一个demo 2. configs详解——之成员 3. configs详解——之field 4. configs详解——之site, page和console 5. configs详解——之回 ...
- Python爬虫(十六)_JSON模块与JsonPath
本篇将介绍使用,更多内容请参考:Python学习指南 数据提取之JSON与JsonPATH JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它是的人们很容易 ...
- 9.json和jsonpath
数据提取之JSON与JsonPATH JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写.同时也方便了机器进行解析和生成.适 ...
- JS学习笔记9_JSON
1.JSON概述 JavaScript Object Natation,js对象表示法,(像XML一样)是一种数据格式,它与js有相同的语法形式 P.S.一点小历史:JSON之父是道格拉斯,<J ...
- JsonPath小结
在查看DHC Assertions 模块说明的时候,无意间发现assert模块中JsonBody使用了 JSON Path ,兴趣使然,看了下,发现是类似解析xml用到的 XPath.通过路径来获取j ...
- 比jsonpath 更方便的json 数据查询JMESPath 使用
类似xml 的xpath json 有jsonpath 都是为了方便进行数据查询,但是jsonpath 的功能 并不是很强大,如果为了方便查询可以使用jmespath. 以下为简单使用: 查询格式 ...
随机推荐
- 测试开发面试的Linux面试题总结之一:vim使用方法
现在做测试没有说不用到linux,大部分公司都会涉及到,作为测试经常使用linux最常见手段就是查看日志,帮助开发定位问题,这是目前最常见的测试当中使用linux方法,今天就讲一讲vim文本编辑器的使 ...
- MySQL数据库无法远程连接的解决办法
远程登陆数据库的时候出现了下面出错信息: ERROR 2003 (HY000): Can't connect to MySQL server on 'xxx.xxx.xxx.xxx', 经过今天下午的 ...
- NOIP2017 宝藏 题解报告【状压dp】
题目描述 参与考古挖掘的小明得到了一份藏宝图,藏宝图上标出了 n 个深埋在地下的宝藏屋, 也给出了这 n 个宝藏屋之间可供开发的 m 条道路和它们的长度. 小明决心亲自前往挖掘所有宝藏屋中的宝藏.但是 ...
- 51nod 1225 数学
F(n) = (n % 1) + (n % 2) + (n % 3) + ...... (n % n).其中%表示Mod,也就是余数. 例如F(6) = 6 % 1 + 6 % 2 + 6 % 3 + ...
- bzoj4873 [Shoi2017]寿司餐厅
Input 第一行包含两个正整数n,m,分别表示这家餐厅提供的寿司总数和计算寿司价格中使用的常数. 第二行包含n个正整数,其中第k个数ak表示第k份寿司的代号. 接下来n行,第i行包含n-i+1个整数 ...
- 组合计数 && Stirling数
参考: http://blog.csdn.net/qwb492859377/article/details/50654627 http://blog.csdn.net/acdreamers/artic ...
- window.location.hash在firefox下中文自动转码为UTF-8问题
1.window.location.hash window.location.hash这个属性主要是读取和写入网页位置的,我们经常会用来控制网页单页面跳转或者是控制网页位置.然而这个属性在firefo ...
- git grep mysql 操作历史
history |grep mysql-----git history匹配出mysql操作的命令 !626 到mysql命令安装处链接mysql /usr/local/mysql/bin/mysql ...
- 「Linux」制作一个Linux系统
一.前言 Linux操作系统至1991年10月5日诞生以来,就其开源性和自由性得到了很多技术大牛的青睐,每个Linux爱好者都为其贡献了自己的一份力,不管是在Linux内核还是开源软件等方面,都为我们 ...
- nginx 与 tomcat 组合搭建web服务
部分内容转自 http://www.cnblogs.com/naaoveGIS/ 1. Web服务 nginx是常用的web服务器,用于获取静态资源,类似的服务器还有apache. tomcat是基于 ...