Ignore Hyphen in Javascript (Postman) - javascript

Building a RestAPI with Postman.
I have some JSON data:
{
"progress-update": {
"#type": "parallel-progress",
"job": {
"#href": "/api/space/job-management/jobs/4691268"
},
"taskId": 4691268,
"jobName": "Compare Config-4691268",
"state": "DONE",
"status": "SUCCESS",
"percentage": 100,
"data": "<![CDATA[Total requests: 3<br>InSync count : 3<br>OutOfSync count : 0<br>]]>",
"subTask": [
{
I want to pull the "state" value into an environment Variable that i can then use to determine wether to continue on to the next request or wait until the state is DONE.
The problem i'm running into is "progress-update": has a hyphen in it, causing my script to not recognize it.
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData.progress-update.state);
Postman returns the following error:
There was an error in evaluating the test script: ReferenceError:
update is not defined

You should be able to access your JSON data with
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData['progress-update'].state);
using the object bracket notation

Related

Parse values in a JSON response array in Postman

I'm trying to parse the value of "id" from the JSON body response to include in an environmental variable in Postman with no success. Here is an example of the Body response.
"payload": {
"transaction": {
"amount": "1.00",
"id": "114255633",
"type": "AUTH",
"result": "APPROVED",
"card": "XXXXXXXXXXXX1111",
"authorization-code": "TAS977",
}
}
and here is my script in postman
var jsonData = JSON.parse(responseBody);
var id = jsonData.payload[0].transaction.id;
postman.setEnvironmentVariable("id", id);
Any help would be appreciated. I think my error is in the way the value I'm looking to get is nested inside an array.
postman provides inbuild method to retrieve json object you don't have to parse it:
Also use the new pm api instead postman
pm.environment.set("id", pm.response.json().payload.transaction.id);
If I am not wrong..This should work
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", jsonData["payload"]["transaction"]["id"]);

Consume AZURE ML with nodejs error 400 status code

I have a problem when I try to consuming the web service, the error is:
The request failed with status code: 400
{"error":
{"code":"BadArgument","message":"Invalid argument provided.",
"details":[{"code":"BatchJobInputsNotSpecified","message":"The following required input(s) were not specified with the request: input1. Please ensure all input data is specified and try again."}]}}
I don't know how to solve that, because in the code I send input1.
Please help me, thanks.
let req = require("request");
const uri = "bla";
const apiKey = "key";
let data = {
"Inputs": {
"input1":
[
{
'IdEmpleado': "20000",
'NivelSatisfaccion': "0.38",
'SatisfaccionLaboral_Disc': "Insatisfecho",
'UltimaEvaluacion': "0.53",
'UltimaEvaluacion_Disc': "Media",
'ProyectosRealizados': "2",
'ProyectosRealizados_Disc': "[2-3]",
'HorasMensuales': "157",
'HorasMensuales_Disc': "[150-199]",
'Antiguedad': "3",
'Antiguedad_Disc': "[2-4]",
'AccidentesTrabajo': "0",
'AccidentesTrabajo_Disc': "NO",
'Ascendido': "0",
'Ascendido_Disc': "NO",
'AreaTrabajo': "Ventas",
'NivelSalarial': "Bajo",
'Renuncia': "1",
'Renuncia_Disc': "SI"
}
],
},
"GlobalParameters": {}
}
The scoring uri expects the body of the request to be a JSON document with the following structure:
{
"data":
[
<model-specific-data-structure>
]
}
The structure of the data needs to match what the scoring script and model in the service expect. Please follow the following document for more information.

How to store Exception/Error from Azure function js?

I have created an Azure function to save data in SQL database from Iot Hub that is working fine, Now I want to save Exception and Error to Azure storage Table so for that I have added try{ } catch(err){} but that is not working. please correct me. Thanks!
my function is here
module.exports = function (context, iotHubMessage) {
try {
var strMsg = JSON.stringify(iotHubMessage);
context.log('Message received: ' + strMsg);
var ob1 = { "employee_idw": 444, "last_name": "Teller", "first_name": "Saara", "age": 34, "salary": 87000 };
//I misspelled 'employee_idw' to generate error
var ob2 = { "employee_id": 555, "last_name": "Teller", "first_name": "Saara", "age": 31, "salary": 87000 };
ob1.EventProcessedUtcTime = new Date;
ob2.EventProcessedUtcTime = new Date;
var arr = [];
arr.push(ob1);
arr.push(ob2);
context.bindings.outputTable = arr;
context.done();
} catch (err) {
context.log('CCC Error' + err); // even can not see this message in log
context.bindings.error= { "partitionKey": partitionKey, "rowKey": rowKey, "data": err };
}
};
see this is JSON file
{
"bindings": [
{
"type": "eventHubTrigger",
"name": "myEventHubMessage",
"path": "myeventhub",
"consumerGroup": "$Default",
"connection": "PBCorIOTHub_events_IOTHUB",
"cardinality": "many",
"direction": "in"
},
{
"type": "apiHubTable",
"name": "outputTable",
"dataSetName": "default",
"tableName": "employees",
"connection": "sql_SQL",
"direction": "out"
},
{
"type": "table",
"name": "error",
"tableName": "dddtTest",
"connection": "cccteststr_STORAGE",
"direction": "out"
}
],
"disabled": false
}
Are you using Azure SQL or Azure table storage to store the data? From your code it looks like you are using Azure table storage. The reason i ask is because a changed property name would not cause an error in function. Instead the table storage would create a new property with misspelled name.
Like Mikhail suggested the to store an error caused inside of a function all you have to do is create another output binding and assign the exception to it.
However not all exceptions occur inside of a function context. For example an error in function.json configuration could cause a error connecting to storage. This would cause function execution to fail outside of function code context. Azure functions has direct integration with Application Insights and can help monitor what you are looking for. Here is a blog post that can shows how to configure Application Insights.
https://blogs.msdn.microsoft.com/appserviceteam/2017/04/06/azure-functions-application-insights/

How to store a value from JSON response in Angular JS

This is my JSON Response of my Rest API.
{"ListClientResponse": {
"Header": {"CMMHeader": {"CorrelationId": "cmm:CorrelationId"}},
"Result": {
"ResponseCode": "CM-N-0000",
"ResponseMessage": "No errors and warnings."
},
"ListClient": {"Client": [
{
"OrganizationId": 523,
"OrganizationName": "OrgX1518521.com",
"OrganizationDomain": "X1518521.com"
],
"RoleId": "AdminRole",
"RoleName": "Admin"
}
},
I want to save Organization Id and OrganizationDomain from my JSON Response in a variables or something so that I can use these values later in my all JSON requests.
This is my JSON request.
var myCreateUserRequest = {
"CreateUserRequest": {
"Header": {
"CMMHeader": {
"CorrelationId": 5454354}},
"ClientContext": {
"OrganizationId": **theOrgId,**
"OrganizationDomain": **theDomain,**
},
"User": {
"UserName": aUser.Username,
"UserPassword": aUser.Password,
"UserStatus": "Active",
"RoleId": "Member"
}
}
}
In my JSON request, inside the field of OrganizationId and OrganizationDomain I want to pass that organizationID value and OrganizationDomain value that I have saved from my JSON Response in a varibale. I want to save it in a way so that organizationId and OrganizationDomain can be accessible in my whole ANGULAR JS project and I can pass it in my any JSON request. How can I do that. Please tell me any suggestion.
Best practice in this case tells to create a service. Becouse services are singleton in Angular, you can set a vale and inject in yours services/controllers and have access to the value.

Check if JSON object exist (Postman)

I am trying to write a test in Postman to check if JSON keys are present in the response I received from the server.
The response:
{
"Result": 0,
"ResponseStatus": {
"ErrorCode": null,
"Message": null,
"StackTrace": null,
"Errors": null
},
"ResponseHeader": {
"Succeeded": true,
"Errors": null
},
"SessionId": "XXX-XXX-XXX"
}
I want to check "Results, Errorcode, Message,Succeeded" etc..
Thanks!
You could check the response scheme using:
var jsonData = JSON.parse(responseBody);
tests['response json contain Results'] = _.has(jsonData, 'Results');
According to your response body that you get, You can write simple test script for request under test section.
You need to parse your json response first. The script will look like:
var jsonData = JSON.parse(responseBody);
tests["Succeeded with value true"] = jsonData.ResponseHeader.Succeeded === true;
similarly you can write tests for other checks.For sessionId I would suggest you to check it with sessionId where it gets generated(store it in environment and check with it in this request)

Categories