Powershell invoke-restmethod then if statement off results - json

I have a working powershell script with invoke-restmethod. The results are pulling back a JSON result and I need to write some if statements off of it to take action. For example, if the status = done then I need to end the application, but if the status = in progress I need to wait 20 minutes then check another field called progressURL.
How do I extract the JSON values based on the key to use in an if statement?
Here is what I have: $response = Invoke-RestMethod WORKING REQUEST THAT RETURNS JSON
Here is the json response
{
"status": done,
"Links": {
"AdditionalData": "someURL1",
"Otherurl": "someURL2",
"progressURL": "someURL3"
}
"ID": 1
}
I just need to take $response that is in JSON and be able to extract values from it to use for if statements.

You'll want to use the ConvertFrom-Json cmdlet to turn your result into a standard PowerShell object - from there it's just standard Boolean comparisons to get where you need to go.
Here's the documentation on ConvertFrom-Json to get you started:
https://technet.microsoft.com/en-us/library/hh849898.aspx

Related

How to pass multiple json objects of array to post request in jmeter using groovy script

POST API is triggering fine and taking only first json object from array and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially using JMeter and Groovy.
json payload : Below is the sample json payload
[
{
"person": "abc",
"Id": "123"},
{
"person": "adfg",
"Id": "12883"},
{
"person": "adf",
"Id": "125"}
]
Groovy code : Reading data from json file which includes multiple json objects and send it to post request in jmeter.
try
{
JsonSlurper jsonSlurper=new JsonSlurper();
def jsonPayload = jsonSlurper.parse(new File('PAYLOAD.json'))
String inputData = new groovy.json.JsonBuilder(jsonPayload)
JsonElement root = new JsonParser().parse(inputData);
JsonArray jsonArray = root.getAsJsonArray();
log.info("jsonArray:"+jsonArray);
if(jsonArray != null && !jsonArray.isEmpty())
{
jsonArray.each{paylodData ->
println paylodData
log.info("post data:"+paylodData);
vars.putObject("payloads", paylodData.toString())
log.info('Generated body: ' + vars.getObject('payloads'))
}
}
}catch (FileNotFoundException fe) {
log.info("Error: Please Check the file path");
}
JMeter Test : Triggering same API with multiple payloads
using below variable in post request body
${payloads}
NOTE : API is triggering fine and taking only first json object and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially.
What are you trying to achieve?
You have a foreach loop which iterates the JSON Array and writes the inner object value into a payloads JMeter Variable
The point is that each iteration of the foreach loop overwrites the previous value in the variable so you will always get the last value.
You either need to replace jsonArray.each with jsonArray.eachWithIndex and store each array member into a separate variable like:
payload_0 = first array member
payload_1 = second array member
etc.
or transform the response into another format, but here I cannot suggest anything because I don't know what is the expected one.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

Azure Data Factory - forEach - JSON to array errors

My aim is to use Azure Data Factory to copy data from one place to another using REST API.
The first part of the copying is using the ForEach activity to select parameters from a nested JSON/array. I have had problems with this nested JSON because of various error messages in the ForEach activity.
My JSON is of the following form:
(
{
"key_1": "value_1",
"key_2": [
"value_2_1",
"value_2_2"
]
}
)
and first I'm setting the #json conversion function in front of it:
#json(
'{
"key_1": "value_1",
"key_2": [
"value_2_1",
"value_2_2"
]
}'
)
Here you can see the Execute Pipeline object and its parameters:
I am setting this JSON as a parameter in the Execute Pipeline object. I am setting its type as an "Array". (For the record, I have still had similar error messages even though I have tried to change the parameter type to "String" or "Object".)
The ForEach activity is used to select an item from the nested JSON, which is written into a parameter.
This immediately produces the following error in the Execute Pipeline activity:
Operation on target... ...failed: The function 'length' expects its parameter to be an array or a string. The provided value is of type 'Object'.
So, even though I set the JSON parameter type to "Array", it is changed into "Object" when I debug the pipeline activity. See the error below:
Next, I tried to use the ADF #createArray function before my JSON text.
#createArray(
'{
"key_1": "value_1",
"key_2": [
"value_2_1",
"value_2_2"
]
}'
)
When debugging, the forEach activity throws me an error in the first Copy data activity:
The expression 'concat(item().SELECTING_key_1_FROM_MY_JSON))' cannot be evaluated because property 'key_1' cannot be selected. Property selection is not supported on values of type 'String'.
Please help me, what I am doing wrong in my attempts of converting the JSON to an array? What should I change in my code?
So far I have tried changing the parameter type and using various functions in the JSON dynamic content but with no luck.
update:
If you want change the filename in Copy Data --> Sink.
You can key in the dynamic content #concat(pipeline().parameters.Pip_Object.key_1,'.json') to rename the file.
Please correct me if I understand you wrong.
First, we should use Parameters to store the Json array as follows. Because Variables are not support to store the Json array. Variables are only support to store simple data type such as ["1","2","3"...].
Json array format should as follows:
[{"key_1": "value_1"},{"key_2": ["value_2_1","value_2_2"]}]
I created a simple test here. Then ForEach the Json array:
Inside ForEach1 activity, pass #item() to the object type parameter Pip_Object.
The Input is as follows:
Add dynamic content above using any combination of expressions, functions and system variables at for each settings
#activity('Get Metadata1').output.childItems
We ended up using two pipelines: a generic one and a specific one.
The generic one has the JSON as a parameter (JSON_PARAMETER), and we set it a default value in the following form
[{"key_1":"value_1","key_2":["value_2"]},{"key_1":"value_3","key_2":["value_2"]}, ...etc. ...}]
The generic pipeline has a forEach loop, in which that mentioned JSON parameter is called in Settings -> Items:
#JSON(pipeline().parameters.JSON_PARAMETER)
In the specific pipeline, there is an Execute Pipeline activity, where the JSON_PARAMETER is found in Settings -> Parameters. If the default value of JSON_PARAMETER is used, the field is left blank. If we want to change the parameter, before Execute Pipeline, we put a Set Variable activity where we change the Variables -> Value to:
#concat('
[
{"key_1":"value_1",
"key_2":
["value_2",
"value_3"
]
},
{"key_1":"value_3",
...and so on...
}
]
')

passing parameter with space into AWS cli

I am trying to pass pass parameter with space to aws cloudformation create-stack aws cli.
The issue is that my parameter has space. I am using powershell for scripting.
Below is example of my parameter
$JsonParameter = '[{"ParameterKey":"name","ParameterValue":"John"},{"ParameterKey":"Occupation","ParameterValue":"Test Engineer"}]'| ConvertTo-Json
This returns
"[{\"ParameterKey\":\"name\",\"ParameterValue\":\"John\"},{\"ParameterKey\":\"Occupation\",\"ParameterValue\":\"Test Engineer\"}]"
cli command is
aws cloudformation create-stack --stack-name $stackName --template-url $templateUrl --capabilities $capabilityList --parameters $JsonParameter --region "us-east-1"
The error goes
Error parsing parameter '--parameters': Invalid JSON:
[{"ParameterKey":"name","ParameterValue":"John"},{"ParameterKey":"Occupation","ParameterValue":"Test
From the error, it looks like cli doesn't like the space in the ParameterValue.
How do I escape the space, so that cli doesn't complain about the space in the value?
Remove | ConvertTo-Json.
Your string is already a json string so you do not want to perform a conversion.
$JsonParameter = '[{"ParameterKey":"name","ParameterValue":"John"},{"ParameterKey":"Occupation","ParameterValue":"Test Engineer"}]'
Just use the string as is.
Alternate scenario
Should you be working with a Powershell object rather than a json string, you might want at some point to convert it into a json to pass it as parameter to your aws call.
That's the moment where ConvertTo-Json would reveal itself to be useful.
Take this for instance
$JsonParameter = #(
#{
ParameterKey = 'name'
ParameterValue = 'John'
},
#{
ParameterKey = 'Occupation'
ParameterValue = 'Test Engineer'
}
)
This is a Powershell object, for which you might had, in a different context, built from scratch with the intent of passing it as a json paramerter to your aws call.
Now, to achieve the transition from this state of "array of hashtables" to a valid json string, you need to use the ConvertTo-Json cmdlet.
$JsonParameterString = $JsonParameter | Convertto-json -Compress
The resulting string he same as you had initially, ready to be passed down to aws :
[{"ParameterKey":"name","ParameterValue":"John"},{"ParameterKey":"Occupation","ParameterValue":"Test Engineer"}]
If on the other hand, you had a json string and needed to edit it without fuss, you could use the ConvertFrom-Json cmdlet, then edit the resulting object as needed and convert it back to json again before passing it down.
Additional note
In my Powershell to Json example,
I used the -compress switch parameter. This is optional. This will create a compressed json string (one line) instead of an expanded one.
Reference
Powershell doc - ConvertTo-Json

Length is not worked in JSON Extractor in Jmeter

I need to get the count of card from json file. For this I've used $.storedCards.cards.lenght
in JSON Extractor but it doesn't work. There is an error message:
Options AS_PATH_LIST and ALWAYS_RETURN_LIST are not allowed when using path functions!
After that I've tried JSR223 PostProcessor with next script on goovy
def jsonText = '''${AllCards}''' //${AllCards} has json value
def json = new JsonSlurper().parseText(jsonText)
log.info( "Json length---------->"+json.resource.size())
${CardsCount} = props.get("4") //vars.put(json.resource.size.toString())
but there is problem with set value to my variable. Or when i've created variable in Groovy it was impossible to use outside from script.
My json file
"storedCards":
{
"cards":
[
{
"CardId":"123",
"cardBrand":"Visa",
"lastFourDigits":"2968",
},
{
"CardId":"321",
"cardBrand":"Visa",
"lastFourDigits":"2968",
},
..........
],
How can i get the count of card and set to my Variables? what should i use for this?
Your JSON data seems to be invalid. Assuming you have the valid JSON like below, I'm answering your question.
{
"storedCards": {
"cards": [
{
"CardId": "123",
"cardBrand": "Visa",
"lastFourDigits": "2968"
},
{
"CardId": "321",
"cardBrand": "Visa",
"lastFourDigits": "2968"
}
]
}
}
You dont need to write Groovy code, you can resolve this using JSON Extractor. Instead of using length function, use JSON path predicate like this-
$.storedCards.cards[*]
Though Variable you used in JSON Extractor won't give the solution right away, another JMeter function helps - __RandomFromMultipleVars
Excerpt from documentation -
The RandomFromMultipleVars function returns a random value based on the variable values provided by Source Variables.
The variables can be simple or multi-valued as they can be generated by the following extractors:
Boundary Extractor
Regular Expression Extractor
CSS Selector Extractor
JSON Extractor
XPath Extractor
XPath2 Extractor
Multi-value vars are the ones that are extracted when you set -1 for
Match Numbers. This leads to creation of match number variable called
varName_matchNr and for each value to the creation of variable
varName_n where n = 1, 2, 3 etc.
So once you use the predicate, you will get the count in the yourVariableName_matchNr. Example:-
Hope this help.

Need help parsing JSON with PowerShell

I have the JSON block below that I am trying to parse with PowerShell. What the JSON is for is to denote permissions that an AD group should be given on an Azure App Registration. An application will have multiple groups assigned to it and each group will have a unique set of roles (permissions). The full JSON file has several of these application blocks.
Basically, what I want to be able to do with PowerShell is to take the application, query Azure AD to get the application resource and then modify the resource to assign each group to the app with its roles using New-AzureADGroupAppRoleAssignment.
Conventional thinking would be the I need a loop nested inside of a loop nested inside of a loop where the first loop grabs the application block, then the second loop grabs the groupname block and then the third loop grabs the array of roles for that group.
"application":
[
{
"groupname": "adgroup1",
"roles": [
"Permission1",
"Permission2",
"Permission3",
"Permission4",
"Permission5",
"Permission6"
]
},
{
"groupname": "adgroup2",
"roles": [
"Permission1",
"Permission2",
"Permission4",
"Permission5",
"Permission6"
]
}
Something like this should get you started
$json = SomethingThatGetsJson | ConvertFrom-Json
$json.application | % {
$data = $_
Write-Host $data.groupname
$data.roles | % {
$role = $_
Write-Host $role
}
}
% is shorthand for ForEach-Object if you want to get some more details on that. $_ is the element value in the current iteration of the enumeration.
So long as the JSON returned is valid you should use the ConvertFrom-Json cmdlet, It will convert the JSON string in to a proper object you can dot walk through and run your other standard cmdlets against like select, where, foreach etc