I would like to get the value of the "currentApproversStr:" based on the condition "status":"Ready for Review" from the below JSON Response body of a HTTP sampler and pass to following HTTP sampler.
I tried the below but it's not working
Names of created variables: currentApproversStr
JSON Path expressions: $.[?((#.currentApproversStr == "Validation, Civa" || #.currentApproversStr == "Validation, Darla" || #.currentApproversStr == "Validation, Bittl" || #.currentApproversStr == "Validation, Cha" || #.currentApproversStr == "Validation, Barnett" ) && #.status== "Ready for Review")]
Match No: -1 OR 1
But Dummy Sampler returns the Results
We can't guarantee the order of the "timecardId" block with the "status":"Ready for Review" i.e some times 2 nd place, some times last. In this it's 2nd block. So not sure Match No: what should i give
[
{
"timecardId": 170803,
"entryHeaderId": "db9341a9-32e8-4d45-a858-a88b75a42cef",
"startsOn": "2021-10-24T00:00:00",
"endsOn": "2021-10-30T00:00:00",
"worksightStatus": "SignedOff",
"projectId": 1977,
"userId": 60874,
"status": "Submitted for Approval",
"batchId": 39814,
"emergencyType": "",
"htgDealMemoId": "0d0ff42b-5c4b-4695-b527-34dfc64585e5",
"unionId": "1c77c660-28fc-4e40-b557-132f3da39597",
"currentApproversStr": "Perf, PA",
"commentStr": "",
"commentUserName": "",
"commentCreatedAt": "1900-01-01T00:00:00",
"occupationCode": "TECHNICIAN",
"activeApprovalFlowId": 166669,
"isAllowanceOnly": false,
"departmentId": null,
"datePosted": null
},
{
"timecardId": 170807,
"entryHeaderId": "c9809446-b01f-4f42-add6-9b441c3d0114",
"startsOn": "2021-10-17T00:00:00",
"endsOn": "2021-10-23T00:00:00",
"worksightStatus": "Outstanding",
"projectId": 1977,
"userId": 60874,
"status": "Ready for Review",
"batchId": 39815,
"emergencyType": "",
"htgDealMemoId": "0d0ff42b-5c4b-4695-b527-34dfc64585e5",
"unionId": "1c77c660-28fc-4e40-b557-132f3da39597",
"currentApproversStr": "Validation, Civa",
"commentStr": "",
"commentUserName": "",
"commentCreatedAt": "1900-01-01T00:00:00",
"occupationCode": "TECHNICIAN",
"activeApprovalFlowId": 166674,
"isAllowanceOnly": false,
"departmentId": null,
"datePosted": null
},
{
"timecardId": 170802,
"entryHeaderId": "db9341a9-32e8-4d45-a858-a88b75a42cef",
"startsOn": "2021-10-24T00:00:00",
"endsOn": "2021-10-30T00:00:00",
"worksightStatus": "SignedOff",
"projectId": 1977,
"userId": 60874,
"status": "Submitted for Approval",
"batchId": 39814,
"emergencyType": "",
"htgDealMemoId": "0d0ff42b-5c4b-4695-b527-34dfc64585e5",
"unionId": "1c77c660-28fc-4e40-b557-132f3da39597",
"currentApproversStr": "Perf, PA",
"commentStr": "",
"commentUserName": "",
"commentCreatedAt": "1900-01-01T00:00:00",
"occupationCode": "TECHNICIAN",
"activeApprovalFlowId": 166669,
"isAllowanceOnly": false,
"departmentId": null,
"datePosted": null
}
]
PROBLEM:
The reason is that you misunderstand the way JSON extractor works. This feature allows you extract many variables in one setting, but number of Names of created variables = number of JSON Path expressions = number of Default Values.
For example, you want to extract 2 variables:
Names of created variables: var_name_1; var_name_2
JSON Path expressions: json_expression_1; json_expression_2
Default Values: default_1; default_2
(Note: remember using semicolon (;) to separate values)
But you set 1 Variable, 1 json expression with MANY default values --> mismatch.
SOLUTION:
You can setup like this:
Names of created variables: currentApproversStr
JSON Path expressions: $.[?(#.status== "Ready for Review")].currentApproversStr
Match No: -1
Default Values: NOT_FOUND
Result:
currentApproversStr_1=Validation, Civa
currentApproversStr_matchNr=1
"Match No" works as follows: if your query returns more than 1 result:
0 - returns random result
-1 - returns ALL results in form of:
currentApproversStr_1 - first match
currentApproversStr_2 - second match
etc.
currentApproversStr_matchNr - total number of matches
any positive integer - returns the given match
It applies not only to JSON Extractor but to all other JMeter PostProcessors which extract values from responses.
You can see generated JMeter Variables using Debug Sampler and View Results Tree listener combination:
Related
I have a table called api_details where i dump the below JSON value into the JSON column raw_data.
Now i need to make a report from this JSON string and the expected output is something like below,
action_name. sent_timestamp Sent. Delivered
campaign_2475 1600416865.928737 - 1601788183.440805. 7504. 7483
campaign_d_1084_SUN15_ex 1604220248.153903 - 1604222469.087918. 63095. 62961
Below is the sample JSON OUTPUT
{
"header": [
"#0 action_name",
"#1 sent_timestamp",
"#0 Sent",
"#1 Delivered"
],
"name": "campaign - lifetime",
"rows": [
[
"campaign_2475",
"1600416865.928737 - 1601788183.440805",
7504,
7483
],
[
"campaign_d_1084_SUN15_ex",
"1604220248.153903 - 1604222469.087918",
63095,
62961
],
[
"campaign_SUN15",
"1604222469.148829 - 1604411016.029794",
63303,
63211
]
],
"success": true
}
I tried like below, but is not getting the results.I can do it using python by lopping through all the elements in row list.
But is there an easy solution in PostgreSQL(version 11).
SELECT raw_data->'rows'->0
FROM api_details
You can use JSONB_ARRAY_ELEMENTS() function such as
SELECT (j.value)->>0 AS action_name,
(j.value)->>1 AS sent_timestamp,
(j.value)->>2 AS Sent,
(j.value)->>3 AS Delivered
FROM api_details
CROSS JOIN JSONB_ARRAY_ELEMENTS(raw_data->'rows') AS j
Demo
P.S. in this case the data type of raw_data is assumed to be JSONB, otherwise the argument within the function raw_data->'rows' should be replaced with raw_data::JSONB->'rows' in order to perform explicit type casting.
I need to check whether or not an entry is present in the data output from a REST call. The JSON output looks something like this:
{
"entity": {
"entries":[
{
"ID": "1",
"Pipeline": "Pipeline_1",
"State":"Completed"
}
],
"duration":1074,
"create_time":"2010-10-10"
}
}
I want to check if for example, Pipeline_1 is missing, then I want the pipeline to print out that 'Pipeline_1 is missing', if not - null. I have tried using the ternary (?) expression:
!$Pipeline.contains ("Pipeline_1") ? "Pipeline_1 is missing" : null && !$Pipeline.contains ("Pipeline_2") ? "Pipeline_2 is missing" : null
I'm having problems with the syntax and I just can't get it right using this method, because it only processes the first query.
I have also tried using the match method, but haven't had success with it either:
match $Pipeline {
$Pipeline!=("Pipeline_1") => 'Pipeline_1 is missing',
$Pipeline!=("Pipeline_2") => 'Pipeline_2 is missing',
_ => 'All of the pipelines have been executed successfully'
}
I have to check for multiple conditions. Any suggestions on how I should nest the conditional expressions? Thank you in advance.
Assuming that you are not splitting the array $entity.entries[*] and processing the incoming document as is, following is a possible solution.
Test Pipeline:
Input:
{
"entity": {
"entries": [
{
"ID": "1",
"Pipeline": "Pipeline_1",
"State": "Completed"
}
],
"duration": 1074,
"create_time": "2010-10-10"
}
}
Expression:
{
"Pipeline_1": $entity.entries.reduce((a, c) => c.Pipeline == "Pipeline_1" || a, false),
"Pipeline_2": $entity.entries.reduce((a, c) => c.Pipeline == "Pipeline_2" || a, false)
}.values().reduce((a, c) => c && a, true) ? "All pipelines executed successfully" : "Pipeline(s) missing"
Output:
If you don't want to do it in a single expression, then you can use a Conditional snap like as follows.
Following is the output of the Conditional snap.
Then you can process it as you please.
I'm using the Robot Framework API automation. Here, storing the JSON response in a variable [POSTResp.content]. I.e., "POSTResp.content" has the whole response, as given below. Please help me to get an attribute's value (for ex, value of referenceId) from the stored content.
Example of JSON response:
{
"serviceResponseHeader": {
"responseContext": {
"responseCode": "MS19",
"responseDescription": "Success",
"serviceResponseTimeInGMT": "18 Sep 2018 16:12:43 GMT"
},
"requesterContext": {
"applicationCode": null,
"applicationSubCode": null,
"countryCode": null,
"requesterReferenceNumber": null,
"requestTimeInGMT": "30 Jun 2015 11:54:49 GMT",
"requesterUserIdentity": "23483",
"requesterGroupIdentity": "1620",
"requesterIpAddress": "",
"sessionIdentity": "2536kjhfdashfkhfsab",
"ssoSessionIdentity": "2536kjhfdashfkhfsab",
"requesterAbbreviatedGroupName": "NEWCOMP"
},
"serviceContext": {
"serviceVersionNumber": "1.0",
"serviceCode": "30"
}
},
"getProxyDetailResponseBody": {
"proxyDetails": {
"proxyType": "",
"proxyValue": "20140005K",
"referenceId": "PR18090000847597",
"transactionId": "18091801657466"
}
}
}
I've tried the below ways,
1) ${json} To JSON ${POSTResp.content} true
log to console \n the Proxy ID is ${json["proxyValue"]}
Result: Resolving variable '${json["proxyValue"]}' failed: TypeError: string indices must be integers, not str
2) ${json} Evaluate json.loads(${POSTResp.content}} json
log to console \n the Proxy ID is ${json["proxyValue"]}
Result: failed: SyntaxError: unexpected EOF while parsing (, line 1)
Issues with your two approaches:
1) the library keyword call passes a true argument (well, truth-like) to the pretty_print parameter:
${json} To JSON ${POSTResp.content} true
Looking at the library's source, in that case the keyword does not return a dict object - but a string, a beatified version of the source json. That coincides with the error your received.
Remove the "true" argument and it must return a dict.
2) In the Evaluate surround the variable with triple quotes (python's literal string):
${json} Evaluate json.loads('''${POSTResp.content}'''}
json
Without it, the framework just dumped the variable's value, which raised a python syntax error.
By the way, try not to make your variables with language keywords/library names - like ${json} up there.
I have a NiFi flow that takes JSON files and evaluates a JSON Path argument against them. It work perfectly except when dealing with records that contain Korean text. The Jayway JSONPath evaluator does not seem to recognize the escape "\" in the headline field before the double quote character. Here is an example (newlines added to help with formatting):
{"data": {"body": "[이데일리 김관용 기자] 우리 군이 2018 남북정상회담을 앞두고 남
북간 군사적 긴장\r\n완화와 평화로운 회담 분위기 조성을 위해 23일 0시를 기해 군사분계선
(MDL)\r\n일대에서의 대북확성기 방송을 중단했다.\r\n\r\n국방부는 이날 남북정상회담 계기
대북확성기 방송 중단 관련 내용을 발표하며\r\n“이번 조치가 남북간 상호 비방과 선전활동을
중단하고 ‘평화, 새로운 시작’을\r\n만들어 나가는 성과로 이어지기를 기대한다”고 밝혔
다.\r\n\r\n전방부대 우리 군 장병이 대북확성기 방송을 위한 장비를 점검하고 있다.\r\n[사
진=국방부공동취재단]\r\n\r\n\r\n\r\n▶ 당신의 생활 속 언제 어디서나 이데일리 \r\n▶
스마트 경제종합방송 ‘이데일리 TV’ | 모바일 투자정보 ‘투자플러스’\r\n▶ 실시간 뉴스와
속보 ‘모바일 뉴스 앱’ | 모바일 주식 매매 ‘MP트래블러Ⅱ’\r\n▶ 전문가를 위한 국내 최상의
금융정보단말기 ‘이데일리 마켓포인트 3.0’ | ‘이데일리 본드웹 2.0’\r\n▶ 증권전문가방송
‘이데일리 ON’ 1666-2200 | ‘ON스탁론’ 1599-2203\n<ⓒ종합 경제정보 미디어 이데일리 -
무단전재 & 재배포 금지> \r\n",
"mimeType": "text/plain",
"language": "ko",
"headline": "국방부 \"軍 대북확성기 방송, 23일 0시부터 중단\"",
"id": "EDYM00251_1804232beO/5WAUgdlYbHS853hYOGrIL+Tj7oUjwSYwT"}}
If this object is in my file, the JSON path evaluates blanks for all the path arguments. Is there a way to force the Jayway engine to recognize the "\"? It appears to function correctly in other languages.
I was able to resolve this after understanding the difference between definite and indefinite paths. The Jayway github README points out the following will make a path indefinite and return a list:
When evaluating a path you need to understand the concept of when a
path is definite. A path is indefinite if it contains:
.. - a deep scan operator
?(<expression>) - an expression
[<number>, <number> (, <number>)] - multiple array indexes Indefinite paths
always returns a list (as represented by current JsonProvider).
My JSON looked like the following:
{
"Version":"14",
"Items":[
{"data": {"body": "[이데일리 ... \r\n",
"mimeType": "text/plain",
"language": "ko",
"headline": "국방부 \"軍 ... 중단\"",
"id": "1"}
},
{"data": {"body": "[이데일리 ... \r\n",
"mimeType": "text/plain",
"language": "ko",
"headline": "국방부 \"軍 ... 중단\"",
"id": "2"}
...
}
]
}
This JSON path selector I was using ($.data.headline) did not grab the values as I expected. It instead returned null values.
Changing it to $.Items[*].data.headline or $..data.headline returns a list of each headline.
I have retrieved remote json using urllib.request in python3 and would like to to dump, line by line, the value of the IP addresses only (ie. ip:127.0.0.1 would be 127.0.0.1, next line is next IP) if it matches certain criteria. Other key values include a score (one integer value per category) and category (one or more string values possible).
I want to check if the score is higher than, say 10, AND the category number equals a list of one OR more values. If it fits the params, I just need those IP addresses added line by line to a text file.
Here is how I retrieve the json:
ip_fetch = urllib.request.urlopen('https://testonly.com/ip.json').read().decode('utf8')
I have the json module loaded, but don't know where to go from here.
Example of json data I'm working with, more than one category:
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
I wrote a simple example that should show you how to iterate trough json objects and how to write to a file:
import json
j = json.loads(test)
threshold = 10
validCategories = ["Test"]
f=open("test.txt",'w')
for ip, categories in j.items():
addToList = False
for category, rank in categories.items():
if category in validCategories and int(rank) >= threshold:
addToList = True
if addToList:
f.write("{}\n".format(ip))
f.close()
I hope that helps you to get started. For testing I used the following json-string:
test = """
{
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
"127.0.0.2" : {
"Test" : "5",
"Prod" : "20"
},
"127.0.0.3" : {
"Test" : "5",
"Prod" : "5",
"Test2": "20"
}
}
"""