0

I am getting below response while running an API.

{
    "bookingId": 0,
    "bookingIds": {
        "13320134": "2023-05-01T04:30:00",
        "13320135": "2023-05-02T04:30:00",
        "13320136": "2023-05-03T04:30:00"
    },
    "conflictDates": null,
    "recurrenceID": 1710459
}

I want to get the first value inside 'bookingIds'

13320134

What I tried:

$.bookingIds.13320134

Output

[
  "2023-05-01T04:30:00"
]

Is it possible using JSON extractor or do I need to achieve this using javascript?

rAJ
  • 1,295
  • 5
  • 31
  • 66

3 Answers3

3

I don't think you can get keys using JSON Extractor.

It's possible with:

  1. JSON JMESPath Extractor:

    query: bookingIds | keys (@) [0]

    enter image description here

    enter image description here

  2. JSR223 PostProcessor with Groovy language:

    new groovy.json.JsonSlurper().parse(prev.getResponseData()).bookingIds.keySet()[0]
    

    enter image description here

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
  • As I added the 'JSON JMESPath Extractor', my HTTP request does not run. Even not visible to any listeners. – rAJ Apr 04 '23 at 12:14
  • Added a [demo](https://i.stack.imgur.com/X4L10.gif) showing JSON JMESPath Extractor confiuguration, if your request is not being executed it indicates improper setup, check [jmeter.log file](https://www.blazemeter.com/blog/jmeter-logging) for any suspicious entries and amend the PostProcessor setup accordingly. – Dmitri T Apr 04 '23 at 12:24
  • As seen in the logs, the API is running but somehow in the UI it is not visible. When I removed the extractor then it is visible again. Strange :) – rAJ Apr 04 '23 at 12:36
2

I guess the Json Extractor is desined to extract the values and not keys.

You can have multiple extractors to do the job for you

  1. Use the json extractor to get the entire bookingIds Object
  2. Use a Regex extractor to filter the first key from the extracted json output

enter image description here

enter image description here

enter image description here

rollno748
  • 334
  • 2
  • 7
  • Or you can use JSR223 pre/postprocessor to cycle through the keys and store it to a variable - it's upto you , how you wanted it to be implemented – rollno748 Apr 04 '23 at 11:36
  • Thanks, It picks the second record instead of first one. – rAJ Apr 04 '23 at 12:22
2

Based upon your comment (as mentioned the second one is getting selected), you can use a JSR223 Post processer and add the following code,

import groovy.json.JsonSlurper;
import java.util.regex.Pattern;


def response = new groovy.json.JsonSlurper().parse(prev.getResponseData());
def bkId = [];

response.bookingIds.each { bookingIdsFetched-> 
    bkId << bookingIdsFetched
}
def value = bkId[0].toString();
def pattern = Pattern.compile('(.+?)=');
def (_, refValue) = (value =~ pattern)[0]

log.info("Reference Value : "+refValue)

enter image description here

Jyoti Prakash Mallick
  • 2,119
  • 3
  • 21
  • 38