1. 程式人生 > 其它 >Json解析案例-teachers資料集

Json解析案例-teachers資料集

背景:teachers資料集,以及對應使用JosnPath。 用途:對Json字串通過指定路徑來獲取相關的一個或多個值。

一、Json字串:

 1 {
 2     "lemon": {
 3         "teachers": [
 4             {
 5                 "id": "101",
 6                 "name": "華華",
 7                 "addr": "湖南長沙",
 8                 "age": 25
 9             },
10              {
11                 "id": "102",
12                 "name": "韜哥
", 13 "age": 28 14 }, 15 { 16 "id": "103", 17 "name": "Happy", 18 "addr": "廣東深圳", 19 "age": 16 20 }, 21 { 22 "id": "104", 23 "name": "歪歪", 24 "
addr": "廣東廣州", 25 "age": 29 26 } 27 ], 28 "salesmans": [ 29 { 30 "id": "105", 31 "name": "毛毛", 32 "age": 17 33 }, 34 { 35 "id": "106", 36 "name
": "大樹", 37 "age": 27 38 } 39 ] 40 }, 41 "avg": 25 42 }

二、JsonPath程式碼

 1 $.lemon.teachers[*].name
 2 
 3 獲取所有老師的的名稱
 4 
 5 $..name
 6 ..name
 7 獲取所有人的名稱
 8 
 9 $.lemon.*
10 所有的老師和銷售(沒有指定屬性,無法直接顯示)
11 
12 $.lemon..age
13 $..age
14 所有人的年齡
15 
16 $.lemon.teachers[*].age
17 ..teachers[*].age
18 ..teachers..age
19 所有老師的年齡
20 
21 $.lemon.teachers[1].name
22 索引為1(第2個)老師的資訊
23 
24 $..teachers[1,2].name
25 ..teachers[:2].name
26 ..teachers[2:].name
27 ..teachers[0:2].name
28 ..teachers[-1].name   (不支援)
29 ..teachers[-1:].name  (倒數一個)
30 ..teachers[-2:].name (倒數兩個)
31 指定範圍老師的姓名
32 
33 
34 ..teachers[?(@.age< 20)].name
35 所有年齡小於20的年齡資訊
36 
37 
38 ..teachers[?(@.age<=$['avg'])].name
39 小於或等於平均年齡的老師資訊
40 
41 $..teachers[?(@.name=~ /.*PPY/i)].name
42 所有名稱滿足正則表示式的老師資訊 (忽略大小寫)
43 
44 $..name (string型別)
45 ..age  (integer型別)
46 所有的資訊
47 
48 ..teachers.length()   (不支援)
49 老師的數量
50 
51 #演示根據條件選擇(當包含資料有多行時,要取出其中某一行時特別有用)
52 ..teachers[?(@.id=="103")].name (不支援雙引號)
53 ..teachers[?(@.id=='103')].name  
54 ..teachers[?(@.age>=25)].name  
55 指定ID的老師的name ,語法 [?(@.屬性條件表示式)]
56 
57 
58 前面:固定指定屬性
59 現在:遍歷有哪些屬性
60 ..teachers[0:2]
61 遍歷某個節點有哪些子屬性