Last active
January 31, 2016 09:11
-
-
Save zhugw/5d17d6bbe03a9eba473c to your computer and use it in GitHub Desktop.
JsonPath 解析 json demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
[ | |
{ | |
"category": "tag_foo", | |
"tagPrice": [ | |
{ | |
"activeTagDictId": 370, | |
"activePrice": 39 | |
}, | |
{ | |
"activeTagDictId": 371, | |
"activePrice": 68 | |
}, | |
{ | |
"activeTagDictId": 372, | |
"activePrice": 99 | |
} | |
] | |
} | |
] | |
``` | |
//解析json 得到activeTagDictId列表 | |
List<String> idList = JsonPath.read(json, "$..activeTagDictId"); | |
System.out.println(idList); // [370,371,372] | |
//解析json 得到某一activeTagDictId对应的价格 | |
List<String> priceList = JsonPath.read(json, "$..tagPrice[?(@.activeTagDictId==371)].activePrice"); | |
System.out.println(priceList); //[68] | |
--- | |
//java8 解析json得到某一属性列表 对比 | |
List<JSONObject> joList = JSON.parseArray(json, JSONObject.class); | |
List<Long> list = joList.stream().flatMap(o -> o.getJSONArray("tagPrice").stream()) | |
.map(o -> ((JSONObject) o).getLong("activeTagDictId")).collect(toList()); | |
System.out.println(list); // [370, 371, 372] | |
-- | |
使用jq实现上述功能 | |
➜ ~ cat test.json | jq '.[].tagPrice[].activeTagDictId' | |
370 | |
371 | |
372 | |
373 | |
374 | |
➜ ~ cat test.json | jq '.[].tagPrice[]|select(.activeTagDictId==373)|.activePrice' | |
129 | |
参考文档 | |
https://stedolan.github.io/jq/manual/#TypesandValues |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment