我的JSON形状有点像这样:
[{
"bulbasaur": [
"ability": {
"name": "imposter",
"is_hidden": true,
},
"name": "bulbasaur",
"id" : 1
]
},
{
"ivysaur": [
"ability": {
"name": "imposter",
"is_hidden": true,
},
"name": "ivysaur",
"id" : 2
]
},
.
.
.
]
如您所见,我正在使用神奇宝贝数据,并且我想知道是否可以在此JSON上发出请求。像SQL一样,它将返回一个值或一组值(形状像表)。 但是我想要没有make功能,我只想查询... 例如,如果我想要所有带有冒名顶替者的宠物小精灵,请输入查询内容,然后获取宠物小精灵的列表
答案 0 :(得分:0)
是的,您可以在本地使用JSONPath,甚至可以将其复制到您正在编写的文件中,此操作已在此处完成:
var data=[{
"ability": [{
"name": "imposter",
"is_hidden": true
}],
"name": "bulbasaur",
"id" : 1
},{
"ability": [{
"name": "imposter",
"is_hidden": false,
}],
"name": "ivysaur",
"id" : 2
}];
console.log("abilities of ivysaur:");
console.log(jsonPath(data,"$..[?(@.name=='ivysaur')].ability"));
console.log("name of monster with hidden first ability:");
console.log(jsonPath(data,"$..[?(@.ability && @.ability[0].is_hidden)].name"));
/* JSONPath 0.8.0 - XPath for JSON
*
* Copyright (c) 2007 Stefan Goessner (goessner.net)
* Licensed under the MIT (MIT-LICENSE.txt) licence.
*/
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, _vname) {
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;
}
}
(我不得不修改示例,既可以使{}
和[]
嵌套,也可以使两个对象不同)。
答案 1 :(得分:-2)
尝试JSON path 可以达到您想要的效果。它基本上是一个包含在代码中的库。
JavaScript库示例:从json对象获取所有作者。
<!DOCTYPE html>
<html>
<head> <script type="text/javascript" src="jsonpath-0.8.0.js">
</script>
</head>
<body>
<script type="text/javascript">
var data= { "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
}
}
} ;
<!-- query : select all authors -->
var queryResult= jsonPath(data, "$..author");
document.write(queryResult);
</script>
<!-- this will output Nigel Rees,Evelyn Waugh,Herman Melville,J. R. R. Tolkien -->
</body>
</html>