纯aardio代码实现jsonPath。
注意:[(…)],[?(…)] 里面的表达式要用aardio对应对象方法操作。
import web.json;
namespace myplu
class jsonPath {
ctor( jsn ) {
if(type(jsn) !== "table"){
jsn = ..web.json.parse(jsn);
}
this._jsonObj = jsn;
};
type = "myplu.jsonPath";
_REGEX_PARENT = ".."; // 用来跨级查找 ..
_REGEX_POINT = "\[\(([\w\W]+)\)\]"; // 表达式转为下标值 [(…)]
_REGEX_FILTER = "\[\??\(([\w\W]+)\)\]"; // 条件过滤 [?(…)]
_REGEX_SLICE = "\[\s*(-?\d*)\s*\:\s*(-?\d*)\s*\:?\s*(\d*)\s*\]"; // 数组分割 [start:end:step]
_normalize = function(expr) {
// 提取[…]格式
var pattern = "%\[\]"
var sub = ..string.matches(expr, pattern);
// 将[…]先去掉
var str = ..string.replace(expr, "%\[\]", ";[#]");
// 然后将.;替换成;
str = ..string.replace(str, "\.;?", ";");
// 去掉多余的空白符
str = ..string.replace(str, "\s+", "");
// 还原..符号
str = ..string.replace(str, ";{2,}", ";..;");
// 拆分表达式
str = ..string.split(str, ";");
for (k, v in str) {
// 还原[…]表达式
if (v === "[#]") {
var t = ..table.remove(sub);
t = t[1];
// 格式化 [p1,p2,p3] [\d:\d:\d] [*] 表达式
if (..string.find(t, "^[\[\]\s\d-,\:\*]+$")) {
t = ..string.replace(t, "\s", "");
}
else {
// 格式化 [?(…)] [(…)] ["p1","p2","p3"]表达式
t = ..string.replace(t, "^\[\s*", "[");
t = ..string.replace(t, "\s*\]$", "]");
}
// [\d] ["key"] ['key'] [\d,\d] ["key","key1"] 转为值或数组
if(..string.find(t,this._REGEX_SLICE) or ..string.find(t,this._REGEX_FILTER)){
}else {
t = ..web.json.parse(t);
select(#t) {
case 0 {
t = "*";
}
case 1 {
t = t[1];
}
}
}
str[k] = t;
}
}
return str;
};
_eval = function (exp,_v) {
if(type(_v) !== "table"){
return ;
}
exp = ..string.replace(exp,"\@","_v");
//..console.log(exp,_v);
var f = assert( loadcode("var _v = ...;return (" + exp + ")") );
return f(_v);
};
_trace = function(index, value, jMap, parent) {
// 是否跨级查找
var loc = parent: jMap[index];
// 有表达式才查找
if (loc) {
// 查找目标为对象,而且有表达式才执行查找
if(type(value) == "table"){
if (value[[loc]]) {
// 直接取值
this._trace(index + 1, value[[loc]], jMap);
}
elseif(..table.isArray(loc)){
// ["key"] ['key'] [1] [p1,p2,p3] ["p1","p2","p3"]
for(k,v in loc){
this._trace(index, value, jMap, v);
}
}
elseif(loc === "*") {
// [*]
for (k, v in value) {
this._trace(index + 1, v, jMap);
}
}
elseif(loc === this._REGEX_PARENT) {
// ..
this._trace(index + 1, value, jMap);
for (k, v in value) {
this._trace(index, v, jMap, this._REGEX_PARENT);
}
}
elseif(..string.find(loc, this._REGEX_SLICE) && ..table.isArray(value)) {
// [start:end:step] 数组类型
var step = ..string.matches(loc, this._REGEX_SLICE);
var st, ed, sp = ..table.unpack(step[1]);
var res = ..table.slice(value, tonumber(st), tonumber(ed));
for (i = 1; #res; tonumber(sp)) {
this._trace(index + 1, res[i], jMap);
}
}
elseif(..string.find(loc, this._REGEX_POINT) && ..table.isArray(value)) {
// [(…)]
var point = ..string.match(loc, this._REGEX_POINT);
var res = this._eval(point, value);
if(!res){
return ;
}
if(type(res) == "table"){
for(k,v in res){
this._trace(index, value, jMap, v);
}
}else {
this._trace(index, value, jMap, res);
}
}
elseif(..string.find(loc, this._REGEX_FILTER) && ..table.isArray(value)) {
// [?(…)]
var filter = ..string.match(loc, this._REGEX_FILTER);
//..console.dump(loc,value);
for(k,v in value){
var res = this._eval(filter, v);
if(res){
this._trace(index+1, v, jMap);
}
}
}
}
}
else {
//..console.dump(value);
// 非对象直接返回查找结果
..table.push(this.resultItems,value);
}
};
["selectList"] = function(jsonpath, node) {
node := this._jsonObj;
if(type(node) !== "table"){
node = ..web.json.parse(node);
}
var jMap = this._normalize(jsonpath);
//..console.dump(jMap);
this.resultItems = {};
this._trace(2, node, jMap);
var res = this.resultItems;
return res;
};
["select"] = function(jsonpath, node) {
var res = this.selectList(jsonpath, node);
if(#res){
return res[1];
}
};
}
namespace jsonPath;
/*****intellisense(myplu)
jsonPath = 导入jsonPath库
jsonPath(__) = 创建jsonPath选择器,@1 为json字符串或者table对象。
jsonPath() = !myjpObj.
end intellisense*****/
/*****intellisense(!myjpObj)
selectList(__) = 抽取列表。@1 为jsonPath表达式, @2 可选,抽取对象。\n 参考:https://goessner.net/articles/JsonPath/
select(__) = 抽取单值。@1 为jsonPath表达式, @2 可选,抽取对象。\n 参考:https://goessner.net/articles/JsonPath/
end intellisense*****/
简单测试:
import console;
import myplu.jsonPath;
var a = `[{"searchValue":null,"createBy":"***","createTime":"2023-12-16 19:02:29","updateBy":"***","updateTime":"2024-03-15 08:33:40","remark":null,"params":{},"newRoleIds":null,"newRole":null,"onlineNumber":null,"sysPost":null,"userid":null,"id":794,"productName":"德国马牌235/50R19 99V FR UC6 SUV","productShortName":"德国马牌ContinentalUltraContact UC6 SUV","productCode":"TMTP2023121619003","materialCode":"017001-01100","partNumber":null,"productTypeId":36,"productTypeName":"德国马牌","productTypeParentId":6,"productTypeParentName":"品牌轮胎","productSaleType":1,"productCategory":1,"productBrandId":12,"productBrandName":"德国马牌","productBrandEnglishName":null,"productMiniLogo":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/minilogo/shopmall_product_info/b5fe0f1b4ad0424cb9a207b5f7452aab.png","productLogoImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/772a929e3cb442b284c539b406abe4c1.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/3cbdfa4845ba47fd897dc34da9431832.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/61a6eb58c847485abc199c8c15ab6c2a.png","productDesc":null,"productDescImgSrcs":null,"imgAccessoryId":null,"productDescImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/descimg/shopmall_product_info/c84af353e394417e8f8a4b509ac9b27c.png","productCrossedPrice":null,"productSalePrice":1099.0,"productSupplier":"大陆马牌轮胎(中国)有限公司","productMaker":"大陆马牌轮胎(中国)有限公司","productModel":"UltraCont UC6 SUV","productSpecs":"235/50R19","productSaleLabel":null,"productUnit":"条","productMinSaleNum":1,"productVirtualSaleNum":2,"productSaleTotal":null,"productSingleMaxnum":4,"productCusMaxnum":null,"aftersaleDesc":null,"productSaleOrg":1,"productServiceType":null,"productShowStatus":1,"productSaleStatus":1,"isHomepageShow":0,"buyQuantity":null,"showPage":2,"showActivityId":null,"isFit":0,"isHaveGift":1,"isHaveActivity":0,"activityName":null,"isHaveCoupon":1,"productLabels":["防滑","静音"],"activityLabels":null,"tireSize":"2
35/50 R19
","tireLoad":"775","tireSpeed":"240","tireFigure":null,"tireDiameter":null,"tireWidth":null,"tireAspectRatio":null,"supplierCode":null,"saleNum":"已售 2","shopmallProductBrand":null,"giftProducts":null,"activityInfos":null,"number":null,"activityLabel":null,"giftCount":4,"productLabel":"防滑,静音","sales":null,"reduceSales":null,"bannerImg":null,"detailImg":null,"brandImg":null,"giftDetailImg":null,"giftProductNumRule":null,"couponLabel":34,"sortNum":0,"isHaveStock":null,"specParams":null,"autoGiveCoupon":0,"dot":null},{"searchValue":null,"createBy":"***","createTime":"2023-12-16 19:03:18","updateBy":"***","updateTime":"2024-03-15 08:33:40","remark":null,"params":{},"newRoleIds":null,"newRole":null,"onlineNumber":null,"sysPost":null,"userid":null,"id":795,"productName":"德国马牌235/50R19 103V XL UC6 SUV","productShortName":"德国马牌ContinentalUltraContact UC6 SUV","productCode":"TMTP2023121619004","materialCode":"017001-01543","partNumber":null,"productTypeId":36,"productTypeName":"德国马牌","productTypeParentId":6,"productTypeParentName":"品牌轮胎","productSaleType":1,"productCategory":1,"productBrandId":12,"productBrandName":"德国马牌","productBrandEnglishName":null,"productMiniLogo":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/minilogo/shopmall_product_info/1f6c2ce9782e45258ce4aaeaa3c950f5.png","productLogoImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/0859cb90ad2843cbbbb25ff059f60254.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/c21ff76ce076477aa21f7f5d8bedfcf5.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/e2354958b28e4449b3a4f0bf922d6770.png","productDesc":null,"productDescImgSrcs":null,"imgAccessoryId":null,"productDescImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/descimg/shopmall_product_info/13c9102f0c9f454f8dde77515273a4a6.png","productCrossedPrice":null,"productSalePrice":1159.0,"productSupplier":"大陆马牌轮胎(中国)有限公司","productMaker":"大陆马牌轮胎(中国)有限公司","productModel":"UltraCont UC6 SUV","produ
ctSpecs":"235/50R19","productSaleLabel":null,"productUnit":"条","productMinSaleNum":1,"productVirtualSaleNum":0,"productSaleTotal":null,"productSingleMaxnum":4,"productCusMaxnum":null,"aftersaleDesc":null,"productSaleOrg":1,"productServiceType":null,"productShowStatus":1,"productSaleStatus":1,"isHomepageShow":0,"buyQuantity":null,"showPage":2,"showActivityId":null,"isFit":0,"isHaveGift":1,"isHaveActivity":0,"activityName":null,"isHaveCoupon":1,"productLabels":["防滑","静音"],"activityLabels":null,"tireSize":"235/50 R19","tireLoad":"875","tireSpeed":"240","tireFigure":null,"tireDiameter":null,"tireWidth":null,"tireAspectRatio":null,"supplierCode":null,"saleNum":"已售 0","shopmallProductBrand":null,"giftProducts":null,"activityInfos":null,"number":null,"activityLabel":null,"giftCount":4,"productLabel":"防滑,静音","sales":null,"reduceSales":null,"bannerImg":null,"detailImg":null,"brandImg":null,"giftDetailImg":null,"giftProductNumRule":null,"couponLabel":34,"sortNum":0,"isHaveStock":null,"specParams":null,"autoGiveCoupon":0,"dot":null},{"searchValue":null,"createBy":"***","createTime":"2023-12-16 20:09:53","updateBy":"***","updateTime":"2024-03-15 08:33:40","remark":null,"params":{},"newRoleIds":null,"newRole":null,"onlineNumber":null,"sysPost":null,"userid":null,"id":869,"productName":"德国马牌235/50R19 103V XL FR EC6","productShortName":"德国马牌 EcoContact6 CEC6","productCode":"TMTP2023121620011","materialCode":"017001-01542","partNumber":null,"productTypeId":36,"productTypeName":"德国马牌","productTypeParentId":6,"productTypeParentName":"品牌轮胎","productSaleType":1,"productCategory":1,"productBrandId":12,"productBrandName":"德国马牌","productBrandEnglishName":null,"productMiniLogo":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/minilogo/shopmall_product_info/e424d6f115744c8c9b33ec8433ba0760.png","productLogoImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/41f7960716d84355a90f4d9e37386ddb.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/4e1abb931f6245948
1402069e1267c6c.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/44c7960b72c54f13907d319d4a9418dd.png","productDesc":null,"productDescImgSrcs":null,"imgAccessoryId":null,"productDescImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/descimg/shopmall_product_info/39e0578bbd44448593e5f2e523dae0f2.jpg","productCrossedPrice":null,"productSalePrice":1169.0,"productSupplier":"大陆马牌轮胎(中国)有限公司","productMaker":"大陆马牌轮胎(中国)有限公司","productModel":"EcoContact 6","productSpecs":"235/50R19","productSaleLabel":null,"productUnit":"条","productMinSaleNum":1,"productVirtualSaleNum":0,"productSaleTotal":null,"productSingleMaxnum":4,"productCusMaxnum":null,"aftersaleDesc":null,"productSaleOrg":1,"productServiceType":null,"productShowStatus":1,"productSaleStatus":1,"isHomepageShow":0,"buyQuantity":null,"showPage":2,"showActivityId":null,"isFit":0,"isHaveGift":1,"isHaveActivity":0,"activityName":null,"isHaveCoupon":1,"productLabels":["节油","静音"],"activityLabels":null,"tireSize":"235/50 R19","tireLoad":"875","tireSpeed":"240","tireFigure":null,"tireDiameter":null,"tireWidth":null,"tireAspectRatio":null,"supplierCode":null,"saleNum":"已售 0","shopmallProductBrand":null,"giftProducts":null,"activityInfos":null,"number":null,"activityLabel":null,"giftCount":4,"productLabel":"节油,静音","sales":null,"reduceSales":null,"bannerImg":null,"detailImg":null,"brandImg":null,"giftDetailImg":null,"giftProductNumRule":null,"couponLabel":34,"sortNum":0,"isHaveStock":null,"specParams":null,"autoGiveCoupon":0,"dot":null},{"searchValue":null,"createBy":"***","createTime":"2023-12-16 20:35:12","updateBy":"***","updateTime":"2024-03-15 08:33:40","remark":null,"params":{},"newRoleIds":null,"newRole":null,"onlineNumber":null,"sysPost":null,"userid":null,"id":895,"productName":"德国马牌235/50R19 99V FR CCLXSP","productShortName":"德国马牌ContiCrossContactLX Sport","productCode":"TMTP2023121620039","materialCode":"017001-01541","partNumber":null,"productTypeId":36,"productTypeName":"德国马牌","productTypeParentId":6,"productTypePar
entName":"品牌轮胎","productSaleType":1,"productCategory":1,"productBrandId":12,"productBrandName":"德国马牌","productBrandEnglishName":null,"productMiniLogo":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/minilogo/shopmall_product_info/2015a69b15c84c82be273115ba76e890.jpg","productLogoImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/9f86decf0050496d9165507cac9d7417.jpg","productDesc":null,"productDescImgSrcs":null,"imgAccessoryId":null,"productDescImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/descimg/shopmall_product_info/7c9e6716cda2476ca9772fc2cdaf6778.jpg","productCrossedPrice":null,"productSalePrice":1169.0,"productSupplier":"大陆马牌轮胎(中国)有限公司","productMaker":"大陆马牌轮胎(中国)有限公司","productModel":"CrossCont LX Sp","productSpecs":"235/50R19","productSaleLabel":null,"productUnit":"条","productMinSaleNum":1,"productVirtualSaleNum":0,"productSaleTotal":null,"productSingleMaxnum":4,"productCusMaxnum":null,"aftersaleDesc":null,"productSaleOrg":1,"productServiceType":null,"productShowStatus":1,"productSaleStatus":1,"isHomepageShow":0,"buyQuantity":null,"showPage":2,"showActivityId":null,"isFit":0,"isHaveGift":1,"isHaveActivity":0,"activityName":null,"isHaveCoupon":1,"productLabels":["操控","防滑"],"activityLabels":null,"tireSize":"235/50 R19","tireLoad":"775","tireSpeed":"240","tireFigure":null,"tireDiameter":null,"tireWidth":null,"tireAspectRatio":null,"supplierCode":null,"saleNum":"已售 0","shopmallProductBrand":null,"giftProducts":null,"activityInfos":null,"number":null,"activityLabel":null,"giftCount":4,"productLabel":"操控,防滑","sales":null,"reduceSales":null,"bannerImg":null,"detailImg":null,"brandImg":null,"giftDetailImg":null,"giftProductNumRule":null,"couponLabel":34,"sortNum":0,"isHaveStock":null,"specParams":null,"autoGiveCoupon":0,"dot":null},{"searchValue":null,"createBy":"***","createTime":"2023-12-29 11:29:17","updateBy":"***","updateTime":"2024-03-15 08:33:53","remark":null,"params":{},"newRoleIds":null,"newRole":null,"onlineNumber":null,"sysPost":null,"userid":n
ull,"id":1154,"productName":"米其林轮胎 揽途3 LATITUDE SPORT3 235/50R19 103V Michelin","productShortName":"米其林Michelin 揽途3 LATITUDE SPORT3","productCode":"TMTP2023122911006","materialCode":"017001-03674","partNumber":null,"productTypeId":37,"productTypeName":"米其林","productTypeParentId":6,"productTypeParentName":"品牌轮胎","productSaleType":1,"productCategory":1,"productBrandId":13,"productBrandName":"米其林","productBrandEnglishName":"Michelin","productMiniLogo":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/443d9610c2624800985fa83ef60d8335.png","productLogoImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/443d9610c2624800985fa83ef60d8335.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/fd4537770eb3487daefb220f05a4d532.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/3f7a9ad5bbac4455a71701be3e25f6f6.png,https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/logoimg/shopmall_product_info/db17603d3b2c4d4f97c491f164976bb1.png","productDesc":null,"productDescImgSrcs":null,"imgAccessoryId":null,"productDescImg":"https://tsf.obs.cn-bj1.ctyun.cn/wechat/xcx/product/descimg/shopmall_product_info/7b20f533a9874b2cb9e08409c65783b4.png","productCrossedPrice":null,"productSalePrice":1309.0,"productSupplier":"郑州甲乙丙丁有限公司","productMaker":"米其林","productModel":"LATITUDE SPORT3","productSpecs":"235/50R19","productSaleLabel":"操控","productUnit":"条","productMinSaleNum":1,"productVirtualSaleNum":0,"productSaleTotal":null,"productSingleMaxnum":4,"productCusMaxnum":null,"aftersaleDesc":null,"productSaleOrg":1,"productServiceType":null,"productShowStatus":1,"productSaleStatus":1,"isHomepageShow":0,"buyQuantity":null,"showPage":2,"showActivityId":null,"isFit":0,"isHaveGift":1,"isHaveActivity":0,"activityName":null,"isHaveCoupon":1,"productLabels":["操控"],"activityLabels":null,"tireSize":"235/50 R19","tireLoad":"875","tireSpeed":"240","tireFigure":null,"tireDiameter":null,"tireWidth":null,"tireAspectRatio":null,"suppl
ierCode":null,"saleNum":"已售 0","shopmallProductBrand":null,"giftProducts":null,"activityInfos":null,"number":null,"activityLabel":null,"giftCount":4,"productLabel":"操控","sales":null,"reduceSales":null,"bannerImg":null,"detailImg":null,"brandImg":null,"giftDetailImg":null,"giftProductNumRule":null,"couponLabel":34,"sortNum":0,"isHaveStock":null,"specParams":null,"autoGiveCoupon":0,"dot":null}]`;
var jp = myplu.jsonPath(a);
a = jp.selectList("$.[(table.len(@) - 1 )]")
console.dump(a);
a = jp.selectList(`$.[?(string.find(@["saleNum"],"0") )].saleNum`)
console.dump(a);
a = jp.selectList("$.[?(@.id == 1154)].productName")
console.dump(a);
a = jp.selectList(`$.[?(@["productTypeName"] == '德国马牌' )].productName`)
console.dump(a);
console.pause();