2017-06-21 63 views
1

我解析一個JSON象下面這樣:通配符JsonPath

jobs1: [ 
{ 
    request: { 
    body: { 
     jobID: "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", 
... 
jobs2: [ 
{ 
    request: { 
    body: { 
     jobID: "60e7c286-f936-4f96-87bc-6bd55f107514", 

,並尋找一種方式在JSON路徑中使用通配符。

我在Java中使用RestAssured框架。執行像下面的代碼後:

List<String> ids = get("/state/").path("*.request.body.jobID"); 
System.out.println(ids); 

我期望能獲得:

[79ceeeff-53b9-4645-80bd-95dfca6fe1e9, 60e7c286-f936-4f96-87bc-6bd55f107514] 

而是我得到一個異常:

java.lang.IllegalArgumentException: Invalid JSON expression: 
Script1.groovy: 1: unexpected token: *. @ line 1, column 27. 
         *.request.body.jobID 
         ^

我已經通過這些教程看,但似乎沒有什麼爲我工作:

https://github.com/json-path/JsonPath

http://goessner.net/articles/JsonPath

如何正確使用JsonPath中的通配符?

+0

你試過用'children'而不是'*'? 參考。 https://github.com/rest-assured/rest-assured/wiki/GettingStarted#jsonpath和http://groovy-lang.org/processing-xml.html#_gpath –

+0

@D.Kovács'「children()。 request.body.jobID「'給出'IllegalArgumentException:沒有簽名的方法:java.util.HashMap。children()適用於參數類型:()values:[]' –

+1

我也想弄清楚如何使用通配符。但是如果你需要一個臨時解決方案,下面的工作。 def jsonSlurper = new JsonSlurper(); def jsonResponse = jsonSlurper.parseText(sampleJson); def listOfJobIds = []; jsonResponse.keySet()。each {node - > \t listOfJobIds.add(jsonResponse [node] .request.body.jobID [0]); } log.info listOfJobIds; – canpan14

回答

0

*.[*].request.body.jobID這將提取的JobID的單獨像下面

[ 
    "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", 
    "60e7c286-f936-4f96-87bc-6bd55f107514" 
] 
0

你真的需要wildcards在這裏?這似乎能夠檢索到你所期望的:

..request.body.jobID 

或者更簡單:

..jobID 
0

GOTO http://jsonpath.herokuapp.com/

並給予輸入像給圖像中的綠色框。

你的圖案應該是像下面

*。[*]。request.body.jobID

你的JSON應該像下面

{ 
 
\t jobs1: [{ 
 
\t \t \t request: { 
 
\t \t \t \t body: { 
 
\t \t \t \t \t jobID: "79ceeeff-53b9-4645-80bd-95dfca6fe1e9" 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t } 
 
\t ], 
 
\t jobs2: [{ 
 
\t \t \t request: { 
 
\t \t \t \t body: { 
 
\t \t \t \t \t jobID: "60e7c286-f936-4f96-87bc-6bd55f107514" 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t } 
 
\t ] 
 
}

你會得到結果li柯下面

[ 
 
    "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", 
 
    "60e7c286-f936-4f96-87bc-6bd55f107514" 
 
]

enter image description here