Converting JSON Raw data into Powershell Format - json

I've got a thermal scanner that I'm trying to send triggers to. I'm able to achieve desired results with postman, but I need a standalone script to achieve this so I've been working in powershell. The manufacturer documentation merely specifies a POST as application/json and provide the raw format to be sent in the body as such:
{
"data": [
{
"output": "DO2",
"mode": "ON",
"duration": 5,
"delay": false
}
]
}
Like I said, I have no issues getting the desired result using postman, but I can't figure out how this needs to be formatted in powershell. Powershell isn't complaining about my code, but the device is not accepting the commands like it does from postman, probably because my code is garbage and the device isn't receiving the data correctly. The documentation says to input this data in the body so I have defined the body variable and simply call the variable when Invoke-Restmethod:
$body = ConvertTo-Json #(
'{"data":[
{
"output": "DO2"
"mode": "ON"
"duration": "5"
"delay": false
}
]
}'
)
any help would be appreciated and thanks in advance!

Use ConvertTo-Json on objects that need to be converted to json (JavaScript Object Notation), which basically is text describing objects in a structured way.
It looks like you already have the info for the body as valid json string, so in your case, use a Here-String for the json body:
$body = #'
{
"data": [
{
"output": "DO2",
"mode": "ON",
"duration": 5,
"delay": false
}
]
}
'#
and use that in your Invoke-Restmethod call

Related

ADF pipeline get dynamic count of input parameters

I have a pipeline where I want to pass a JSON to from 3rd party application.
simple JSON Example, but the keys could be different for each call
{
"name": "Here is a name",
"guaid": "123456-123456-123456-111112",
"owner": "my.email#example.com",
"description": "here comes my description"
}
Passing the JSON is not the problem but I do not want to configure each parameter in the JSON as an pipeline parameter inside my ADF because it is not needed.
I do not modify the JSON inside my pipeline, I just have to surround it with some other parameters, so I need it as a whole.
I cloud of course define a parameter for each key in the JSON and concatenate it again but why do the effort if it is not needed.
I also can not modify how the JSON will be passed to my pipeline, so it is not possible to pass the whole JSON inside one parameter like this:
{
"inputParam": "{\"name\": \"Here is a name\",\"guaid\": \"123456-123456-123456-111112\",\"owner\": \"my.email#example.com\",\"description\":\"here comes my description\"}"
}
so is it possible to get all input without "knowing" it and use it in my activity?
My Pipeline is just simple, I only need a set variable and web activities, so I want to avoid a complex solution.
JSON Outbutt should look like this
{
"processingMode": "full",
"version": "1.0.0",
"content": [
{
"type": "Application",
"id": "akjhajf-ffsfsfs-sf-sf-sf",
"data": {
"name": "Here is a name",
"guaid": "123456-123456-123456-111112",
"owner": "my.email#example.com",
"description": "here comes my description"
}
}
]
}
I achieve this by adding this in a set variable like this with the not allowed method i mentioned above
{
"processingMode": "full",
"version": "1.0.0",
"content": [
{
"type": "Application",
"id": "#{guid()}",
"data": #{pipeline().parameters.inputParam}
}
]
}
I then just use this result JSON and call a external Webservice via Web activity

How to find json array length in json extractor

Im using the following JSON and query to calculate the array length in the JMeter json extractor.
{
"data": {
"modal": "HJ",
"technicalid": "e492fc62-a886-67a461b76de8",
"viewModel": {
"series": [
{
"name": "H_0_G_0_R_0",
"UID": "J_0_G_0_R_0",
"description": "Test1",
"type": "series",
"groups": [
{
"name": "H_0_G_0",
"UID": "G_0_G_0",
"description": "Group 1",
"type": "group"
}
],
"postProcessing": null
}
]
},
"status": "success"
},
"success": true,
"statusCode": 200,
"errorMessage": ""
}
Here is the query.
data.Model.series[0].groups.length
This is working fine in the online jsonquerytool. When I use this query in the JMeter json extractor, it is returning null. I assume this is because it is returning an integer because other similar queries which are returning strings are working fine with json extractor . How to find the array length in JMeter json extractor?
Why JSON extractor to calculate the length? You could use a post processer. Like JSR223 post processer using groovy script.
import groovy.json.*
def response = prev.responseDataAsString ;
def json = new JsonSlurper().parseText(response) ;
def sizeResultPractitioners = json.data.viewModel.series[0].groups.size();
log.info("---------->"+sizeResultPractitioners);
I tried with your JSON response payload and also tried with modified response payload,
With modified response payload,
With JSON Extractor you can provide "Match No." as -1:
and the number of matches will be available as foo_matchNr JMeter Variable:
Alternative option is going for JSON JMESPath Extractor which provides length() function so you can get the size of the array as:
length(data.viewModel.series[0].groups)
or if you prefer pipe expressions
data.viewModel.series[0].groups | length(#)

POSTMAN How to parse a nested json object in postman which has dynamic keys?

supposing the json body returned from a call contains some dynamic keys ie
{
"message": "search results matching criteria",
"permission": {
"261ef70e-0a95-4967-b078-81e657e32699": {
"device": {
"read:own": [
"*"
]
},
"account": {
"read:own": [
"*"
]
},
"user": {
"read:own": [
"*"
]
}
}
}
I can validate the json as follows easily enough although I am having a lot of trouble working out how to validate the objects BELOW the dynamic guid level of the response.
pm.test("response body to have correct items", function () {
pm.expect(jsonData.message).to.eq("search results matching criteria");
pm.expect(jsonData).to.have.property('permission');
pm.expect(jsonData.permission).to.have.property(pm.variables.get("otherUserId"));
});
Would ideally like to verify the device and account and user levels of the object.
Anyone with some tips?
I've tried a few ways to try and reference the otherUserId variable but nothing is working. It is either not resolving the variable therefore failing the test as its looking for a level in the json called otherUserId or it fails to run the test due to a syntax error.
This works:
pm.expect(jsonData.permission[pm.variables.get("otherUserId")]).to.have.property('device');

printing json values python

This is my json result from the request
{
"name": "North America",
"region_tag": "na1",
"hostname": "prod.na1.lol.riotgames.com",
"services": [
{
"status": "online",
"incidents": [
{
"active": true,
"created_at": "2018-03-22T10:53:03.397Z",
"id": 7636
}
]
}
]
}
I want to print out the value of status from services
My code
link = "https://na1.api.riotgames.com/lol/status/v3/shard-data?api_key={}".format(API_KEY)
rq_link=rq.get(link).text
rq_json=json.loads(rq_link)
I've tried
print(rq_json['services']['status])
and I get an error saying TypeError: list indices must be integers or slices, not str
Is there another way to do it other than using the for loop
for post in rq_json['services']:
print(rq_json['status'])
The answer you're looking for its
rq_json['services'][0]['status']
Because, the service part is described in a list, you need to specify an index to get into inner dict
You can use list comprehension:
[print(service['status']) for service in rq_json['services']]
More info about list comprehension could be found in the official Python documentation

apigee - Json payload extract variables

I am confused why the extractVariables rule I am using is returning data as it is. See Below.
The json to Parse is:
{
"callNotificationSubscriptionList": {
"playAndCollectInteractionSubscription": [],
"recognitionInteractionSubscription": [],
"playAndRecordInteractionSubscription": [],
"callDirectionSubscription": [],
"callEventSubscription": [
{
"clientCorrelator": "112345",
"resourceURL": "http:someurl",
"callbackReference": {
"notifyURL": "someotherurlt",
"notificationFormat": "XML"
},
"filter": {
"data1": "data abc",
"data2": "data def",
"data3": "data xyz"
}
}
]
}
}
The rule:
<JSONPayload>
<Variable name="callNotSubL">
<!-- <JSONPath>$.callNotificationSubscriptionList</JSONPath> -->
<JSONPath>$.*</JSONPath>
</Variable>
</JSONpayload>
When I use the value that is commented out, I get no response variable data. If I set the "ignoreUnresolvedVariables" parm to "false", I am returned a failure, so it has no data. Thus, I tried "$.*" With this, I am returned:
[
{
"callbackReference": {
"notifyURL": "someotherurlt",
"notificationFormat": "XML"
},
"filter": {
"data1": "data abc",
"data2": "data def",
"data3": "data xyz"
}
}
]
could this be because the EntryNames are so long? I admit they are long, but they are well under the default values in the JSON Threat Potection Policy.
I did pump this json though a web based JSONPayload parser and $.callNotificationSubscriptionList worked fine as did $.callNotificationSubscriptionList.callEventSubscription[0] which is what I am really after. But, if I can't get the top level right, I can't get the sub-levels at all.
I solved this issue using #Santanu's comments:
It seems that the JSON to parse getting through the policy is not same as what you are expecting? Can you try to assign entire payload to a variable using the AssignVariable policy before the JSON path extraction policy, and check the value of that variable in the debug view? That would help understand what payload value is actually passing through when you are trying to apply the json path extraction policy.
the <Source> tag was "request" and this was a response extract. I removed the <Source> tag and all is well