0
votes

In my JMeter test plan, I have a sampler which returns the list of authors and their books in JSON format. I would like get the id of all authors only. That is, In this case, I should get [1,2,3] in a variable name, so that I can use a ForEach controller to initiate another sampler to get detail information about each author. I know I can use JSON extractor to get this, but I am not getting each data that I am looking for.

    [
    	{
    		"firstName": "William",
    		"lastName":"Shakespeare",
    		"Title": "Mr",
    		"id": "1",
    		"books": [
    			{
    				"id": "WS1",
    				"title": "King John",
    				"year":"1596"
    			},
    			{
    				"id": "WS2",
    				"title": "Julius Caesar",
    				"year": "1599"
    			},
    			{
    				"id": "WS3",
    				"title": "Romeo and Juliet",
    				"year": "1595"
    			}
    		],
    		"Nationality": "English"
    	},
    	{
    		"firstName": "Sidney",
    		"lastName":"Sheldon",
    		"Title": "Mr",
    		"id": "2",
    		"books": [
    			{
    				"id": "SS1",
    				"title": "The Naked Face",
    				"year":"1969"
    			},
    			{
    				"id": "SS2",
    				"title": "A Stranger in the Mirror",
    				"year": "1976"
    			},
    			{
    				"id": "SS3",
    				"title": "Bloodline",
    				"year": "1977"
    			}
    		],
    		"Nationality": "American"
    	},
    	{
    		
    		"firstName": "Eiichiro",
    		"lastName":"Oda",
    		"Title": "Mr",
    		"id": "3",
    		"books": [
    			{
    				"id": "EO1",
    				"title": "Wanted",
    				"year":"1992"
    			},
    			{
    				"id": "EO2",
    				"title": "Ikki Yako",
    				"year": "1993"
    			},
    			{
    				"id": "EO3",
    				"title": "Monsters",
    				"year": "1994"
    			}
    
    		],
    		"Nationality": "Japanese"
    	}
    ]

Using JSON Extractor Post processor, when I used JSON Path expression $..id, it gives me all the ids, including ids of books too. For example, it returns [1,WS1,WS2,WS3,2,SS1,SS2,SS3,3,EO1,EO2,EO3]. I think .. in JSON mean recursive lookup, which is not I want. I want the ids only from top level. Can this be achieved using built-in JSON Extractor, or I have to use some sort of Groovy script.

1

1 Answers

1
votes

This .. operator stands for deep scan, if you want only top-level IDs you should use the following JsonPath expression:

$.[*].id

Demo:

enter image description here

More information: API Testing With JMeter and the JSON Extractor