how to remove [] character at extracted json using json path - json

{
"responseCode": "200",
"data": {
"sequence": 1,
"used": true,
"sensingTags": [
{
"code": "LED",
"value": 1,
"updatedOn": 1587557350251
}
]
}
}
My goal is get updatedOn value from this json using jsonPath like this
1587557350251
i thought below jsonPath will work but it extract only empty list.
$..sensingTags[?(#.code == 'LED')][0].updatedOn
And i want to know how to extract value like below
{
"code": "LED",
"value": 1,
"updatedOn": 1587557350251
}
Not like this one.
[
{
"code" : "LED",
"value" : 1,
"updatedOn" : 1587557350251
}
]

As per Getting a single value from a JSON object using JSONPath, JsonPath will always return an array (or a false) at that point...
Best you can do is process it as an array of updatedOn and simply always grab the first value.
$..sensingTags[?(#.code == 'LED')].updatedOn

Related

Json Extractor in JMeter

I am using JSON extractor in JMeter. Below is my Response Body. I am using the Json path expression to capture the value, which is working fine.
Apart from the above condition, I need to add one more condition.
If the "travelID" length is equal to 33, then only I need to get the BoundID.
Example : AAA-AB1234-AAABBB-2022-11-10-1111
Total length or count of the above travelID is 33, but sometime I used to get 31,32 also but I need to capture the Bound ID only when the length is 33. Is that feasible ? Please help on the same
PFB sample response body.
{
"data": {
"RenewalDetails": [
{
"ExpiryDetails": {
"duration": "xxxxx",
"destination": "XXX",
"from": "XXX",
"value": 2,
"segments": [
{
"valudeid": "xxx-xx6262-xxxyyy-1111-11-11-1111"
}
]
},
"Itemdetails": [
{
"BoundId": "xxx-1-xxx1-111111111111-1",
"isexpired": true,
"FamilyCode": "PREMIUM",
"availabilityDetails": [
{
"travelID": "AAA-AB1234-AAABBB-2022-11-10-1111",
"quota": "X",
"scale": "XXX",
"class": "X"
}
]
}
]
}
]
},
"warnings": [
{
"code": "xxxx",
"detail": "xxxxxxxx",
"title": "xxxxxxxx"
}
]
}
I don't think it's possible with JSON Extractor, I would rather suggest going for JSR223 PostProcessor and the following Groovy code:
def BoundId = new groovy.json.JsonSlurper().parse(prev.getResponseData())
.data.RenewalDetails[0].Itemdetails.find { itemDetail ->
itemDetail.availabilityDetails[0].travelID.length() == 33
}?.BoundId
vars.put('BoundId', BoundId ?: 'Not Found')
You will be able to refer extracted value as ${BoundId} later on where required.

Copy value from grandchildren if it exists, use null otherwise

Given the JSON:
{
"id": 1,
"coding": [{
"code": 1234,
"system": "target"
}, {
"code": 5678,
"system": "other"
}]
}
I can select the value of "code" where the "system" is "target", thus:
{id: .id} + {"code": .coding[]? | select(.system=="target").code}
To produce:
{
"id": 1,
"code": 1234
}
But if the object whose "system" value is "target" does not exist in the array, thus:
{
"id": 1,
"coding": [{
"code": 5678,
"system": "other"
}]
}
I want the following result:
{
"id": 1,
"code": null
}
However, my above jq produces an empty object. How can I achieve what I want?
The select built-in yields empty unless at least one of its inputs meets the given criteria, and empty consumes almost anything around itself. Hence the empty result.
Instead, use the first built-in for alternating between the code value from the object where system is target, and null. This also covers some other cases you didn't mention explicitly.
{ id, code: first((.coding[]? | select(.system == "target") .code), null) }
Online demo

How do I give a where clause or condition to get a value in json response using rest asssured

I need to extract the value of id where name == 'abc'. How can I do that?
here is the example of response:
{
"Text": [
{
"id": "123",
"name": "ABC"
},
{
"id": "456",
"name": "XYZ"
},
{
"id": "789",
"name": "DEF"
}
]
}
So I need to extract the value of id where name =='ABC' should return me id value as 123.
I need to use jayway restassured.
Use GPath findAll feature
when().
get("/restapi").
then().
body("text.findAll{ it.name == 'ABC' }.id", hasItem("123"));

Trouble Parsing Array vs Non-Array JSON with JSONPath

I have JSON that looks like the below. I'm trying to use JSONPath to grab the __ content __ value where the SKU is "8A-OK9F-9LI8" AND the Component.Type == 'Principal'. Right now, I am playing around with this JSON Path Expression Tester.
This JSONPath expression grabs all of the component information I need:
$.Order..Fulfillment[?(#.SKU=='8A-OK9F-9LI8')]..Component
But filtering further such as $.Order..Fulfillment[?(#.SKU=='8A-OK9F-9LI8')]..Component[?(#.Type=='Principal')] grabs only one (I believe the Array one) of the two Component elements I need. I suspect this is because one is an Array and one is a single JSON element. Is it possible to grab this with one command or do I have to combine several commands (one for the Array and one for the single JSON element)? If so, how can I grab the other Component information that I am not currently getting with:
$.Order..Fulfillment[?(#.SKU=='8A-OK9F-9LI8')]..Component[?(#.Type=='Principal')]?
Again, my goal is to grab the "__ content__" value and filter by a specific SKU and where the Component.Type == 'Principal'. Something like:
$.Order..Fulfillment[?(#.SKU=='8A-OK9F-9LI8')]..Component[?(#.Type=='Principal')]..Amount..__content__
I'm expecting to get back ["8.49", "8.49"]
Here is the JSON I am testing with:
{
"SettlementData": {},
"Order": [
{
"OrderID": "XXX",
"Fulfillment": {
"Item": {
"SKU": "8A-OK9F-9LI8",
"Quantity": "1",
"ItemPrice": {
"Component": [
{
"Type": "Principal",
"Amount": {
"__content__": "8.49",
"currency": "USD"
}
},
{
"Type": "Tax",
"Amount": {
"__content__": "0.74",
"currency": "USD"
}
}
]
}
}
}
},
{
"OrderID": "XXX",
"Fulfillment": {
"Item": {
"SKU": "8A-OK9F-9LI8",
"Quantity": "1",
"ItemPrice": {
"Component": {
"Type": "Principal",
"Amount": {
"__content__": "8.49",
"currency": "USD"
}
}
}
}
}
}
]
}
I was able to solve this in two passes. In this example, #{sku} is a Ruby interpolated string that contains the SKU I am passing in:
$.Order..Fulfillment[?(#.SKU=='#{sku}')]..ItemPrice..[?(#.Type=='Principal')].Amount.__content__
$.Order..Fulfillment..Item[?(#.SKU=='#{sku}')]..ItemPrice..[?(#.Type=='Principal')].Amount.__content__
Using a Ruby gem "jsonpath", I was able to get the amounts I needed like this:
amount = JsonPath.on(settlement, "$.Order..Fulfillment[?(#.SKU=='#{sku}')]..ItemPrice..[?(#.Type=='Principal')].Amount.__content__")
.map(&:to_f).inject(:+)
amount2 = JsonPath.on(settlement, "$.Order..Fulfillment..Item[?(#.SKU=='#{sku}')]..ItemPrice..[?(#.Type=='Principal')].Amount.__content__")
.map(&:to_f).inject(:+)

how to iterating through json data in python?

I have a json output like below,
{
"took":3,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},
"hits":{"total":2,"max_score":1.0,
"hits":
[
{
"_index":"management",
"_type":"",
"_id":"/home/myfld1/myid1",
"_score":1.0,
"_source" :
{
"newslides": "User Mgmt1 ",
"metaData":
{
"fileName": "file1",
}
}
},
{
"_index":"management",
"_type":"",
"_id":"/home/myfld3/myid3",
"_score":1.0,
"_source" :
{
"newslides": "User mgmt2 ",
"metaData":
{
"fileName": "file2",
}
}
}
]
}
}
I am trying to get the "fileName" field from the above json. I have tried like this,
for filenames in response["hits"]["hits"][0]["_source"]["newslides"]["metaData"]:
filearray.append(filenames["fileName"])
But i am getting one error like below,
for filenames in response["hits"]["hits"][0]["_source"]["newslides"]["metaData"]:
TypeError: string indices must be integers
Please help me to get that file name.
It is simply a dictionary with some lists and other dictionaries in it. Just be careful and go through the elements iteratively:
filearray = []
for x in response["hits"]["hits"]:
filearray.append(x["_source"]["metaData"]["fileName"])
or in one line:
filearray = [x["_source"]["metaData"]["fileName"] for x in response["hits"]["hits"]]