I would like to ask for a help with reading JSON format from a device in Node-Red. I succesfully made to read the JSON content in Python, but applying the same strategy in Node-Red does not yield a success.
I tried several approches.
Use JSON node, it reports
Unexpected token in JSON at position 0
I tried the function node
var str = JSON.stringify(msg.payload);
var data = JSON.parse(str);
// var Temp1 = data["Monitor"]["S"]["S1"]["item1"]["value"];
msg.payload = data["Monitor"]["S"]["S1"]["item1"]["value"];
return msg, data;
And Node-red reports:
> TypeError: Cannot read properties of undefined (reading 'S')
To read the Json from the device I use HTTP get
{
"Monitor": {
"DeviceInfo": {
"DeviceName": "TCW241",
"HostName": "TCW241",
"ID": "5C:32:C5:00:9E:C2",
"FwVer": "TCW241-v1.240",
"MnfInfo": "www.teracomsystems.com",
"SysContact": "Petr",
"SysName": "Garaze Relay",
"SysLocation": "Garaze Anglie"
},
"S": {
"S1": {
"description": "Garaz",
"id": "28245C75D0013C29",
"item1": {
"value": "9.4",
"unit": "°C",
"alarm": "0",
"min": "-40.0",
"max": "85.0",
"hys": "8.5"
},
"item2": {
"value": "---",
"unit": "---",
"alarm": "0",
"min": "---",
"max": "---",
"hys": "---"...
Related
I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.
I have a socket response that is this:
{"op":0,"d":{"author":{"id":"6699457769390473216","name":"Test","verified":false},"unixTime":1597277057132,"id":"6699465549836976128","group":"64632423765273287342","content":"Yo","_id":"5f34838198980c0023fa49e3"},"t":"MESSAGE"}
and I need to access the "d" object, I've tried doing
print(JSON(data)["d"])
and it just Returns null every time.
If data is of type String, you are probably using the wrong init method to initialize the JSON object. Try using init(parseJSON:) like this:
let jsonString = """
{
"op": 0,
"d": {
"author": {
"id": "6699457769390473216",
"name": "Test",
"verified": false
},
"unixTime": 1597277057132,
"id": "6699465549836976128",
"group": "64632423765273287342",
"content": "Yo",
"_id": "5f34838198980c0023fa49e3"
},
"t": "MESSAGE"
}
"""
let json = JSON(parseJSON: jsonString)
print(json["d"])
tests["Valid schema"] = tv4.validate(jsonData, schema); is passed even if "error" and "responseType" is missing in the schema. How to make sure that response and schema both are matching for JSON schema.
when I hit post request on postman, the following is the Response Body in postman
{
"statusCode": 400,
"error": "Bad Request",
"message": "Email/Phone number not found",
"responseType": "EMAIL_NOT_FOUND",
"arabicMessage": "البريد الإلكتروني / رقم الهاتف غير موجود"
}
Tests in Postman
var jsonData=JSON.parse(responseBody)
var schema ={
"statusCode": {"type":"integer"},
"message": {"type":"string"},
"arabicMessage":{"type":"string"},
"data": {
"accessToken": {"type":"string"},
"userDetails": {
"_id": {"type":"string"},
"deviceType": {"type":"string"},
"countryCode": {"type":"string"},
"OTPCode": {"type":"integer"},
"invitationCode": {"type":"string"},
"availableCredits": {"type":"integer"},
"totalBookings": {"type":"integer"},
"promoCodes": {"type":"array"},
"updatedAt": {"type":"string"},
"createdAt": {"type":"string"},
"language": {"type":"string"},
"IsDeleted": {"type":"boolean"},
"IsVerified": {"type":"boolean"},
"IsBlock": {"type":"boolean"},
"customerAddresses": {"type":"array"},
"address":{"type":"string"},
"phoneVerified": {"type":"boolean"},
"currentLocation": {
"type": "Point",
"coordinates": [
{"type":"integer"},
{"type":"integer"}
]
},
"appVersion": {"type":"integer"},
"profilePicURL": {
"thumbnail": {"type":"string"},
"original": {"type":"string"}
},
"password": {"type":"string"},
"socialId": {"type":"string"},
"phoneNo": {"type":"integer"},
"email": {"type":"string"},
"LastName": {"type":"string"},
"firstName": {"type":"string"},
"__v": {"type":"integer"},
"referralCode": {"type":"string"},
"accessToken": {"type":"string"},
"deviceToken": {"type":"string"}
},
"updateAvailable": {"type":"boolean"},
"stateCallBookingIds": {"type":"array"},
"forceUpdate": {"type":"boolean"}
}
};
tests["Valid schema"] = tv4.validate(jsonData, schema);
//here the test is passing even with invalid jsonData which is the data
console.log("Validation failed: ", tv4.error);
There are lots of open issues on the Postman github account about the tv4 module.
There is a similar question on SO here, could your jsonData be different than your schema?
This is an example from a link on the tv4 github page.
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
You could try adding those fields as required?
Just leaving this here in case it helps anyone else. tv4.validate has two additional boolean parameters: checkRecursive and banUnkownProperties.
Especially the last one can help finding errors in JSON responses when they contain attributes that weren't defined in the schema.
Reference
I prefer to use jsonSchema this way:
var strSchema =
pm.collectionVariables.get("variable_that_contains_the_schema");
pm.test("Validate SCHEMA is OK", () => {
pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});
And if you want to auto-generate the schema, you can use the generate-schema plugin https://www.npmjs.com/package/generate-schema
I use to store the content of this plugin in a collection variable, on the pre-request of my collection, like this:
Then in the test tab of your request, you can call the javascript eval() to load the generate-schema source-code in the postman's test environment:
// eval will evaluate the JavaScript generateSchema code and
// initialize the js on postman environment
eval(pm.collectionVariables.get("generate-schema"));
var strSchema =
pm.collectionVariables.get("variable_that_contains_the_schema");
if (strSchema === undefined){
console.log('>>>> variable for schema not defined!');
return;
}
if(strSchema == '' | strSchema === null) {
// call function generateSchema (external)
var schema = generateSchema.json("variable_that_contains_the_schema", jsonData);
delete schema.$schema; // remove the element '$schema' --> causes error in validator
var strSchema = JSON.stringify(schema);
//save the generated schema
pm.collectionVariables.set("variable_that_contains_the_schema", strSchema);
console.log(" >> schema was generated from the response, validation will proceed on the next request.");
}
else
{
console.log(" >> schema recovered from variable.");
// Schema test ------------------------------------------------
pm.test("Validate SCHEMA is OK", () => {
pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});
}
I'm new to rest-assured and I'm currently spiking it in order to implement it in our testing framework.
The problem I'm facing is to extract an object from a Json array from the REST response.
The example json I'm using:
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/2016/drivers.json",
"limit": "30",
"offset": "0",
"total": "24",
"DriverTable": {
"season": "2016",
"Drivers": [
{
"driverId": "alonso",
"permanentNumber": "14",
"code": "ALO",
"url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
"givenName": "Fernando",
"familyName": "Alonso",
"dateOfBirth": "1981-07-29",
"nationality": "Spanish"
},
{
"driverId": "bottas",
"permanentNumber": "77",
"code": "BOT",
"url": "http://en.wikipedia.org/wiki/Valtteri_Bottas",
"givenName": "Valtteri",
"familyName": "Bottas",
"dateOfBirth": "1989-08-28",
"nationality": "Finnish"
}
]
}
}
}
Things i have tried so far:
This assertion is working
RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.assertThat()
.body("find { find { d -> d.driverId == 'alonso' }.code }.code", equalTo("ALO"));
But I'm trying to actually get the Json of the particular array item
RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.extract()
//.jsonPath().param("driverId", "alonso").get("find { d -> d.driverId == driverId }");
.path("find { d -> d.driverId == 'alonso' }");
Tried with both ways (one is commented out). But I get an error :
"The parameter "driverId" was used but not defined. Define parameters using the JsonPath.params(...)"
RestAssured.rootPath = "MRData.DriverTable.Drivers"; works only for body expectations. For extraction you have to use full path to paramter e.g. MRData.DriverTable.Drivers.find { it.#driverId == 'alonso' }
I have a big query table that has a JSON object as one of the field in the table. How can I extract the data from the JSON object using app script. The object itself is nested. It looks like this
{
"uid": "124551",
"subjects": [
{
"tid": 37,
"title": "Algebra",
"html_id": "algebra",
"selected": true
},
{
"tid": 214853,
"title": "Trigonometry",
"html_id": "trigonometry",
"selected": true
},
{
"tid": 38,
"title": "Geometry",
"html_id": "geometry",
"selected": true
}
],
"cellphone": "09178854579",
"educations": [
{
"index": 0,
"schoolname": "University of the Philippines - Los Baños",
"degree": "BS Mathematics",
"major": "Mathematics",
"eduFrom": "2009-05-31T16:00:00.000Z",
"eduTo": "2013-04-26T16:00:00.000Z",
"eduFromTs": 1243785600,
"eduToTs": 1366992000
}
],
"info": {
"os": "Windows",
"internet": "ADSL",
"browser": "Chrome",
"network": "Wireless",
"speed": "",
"timezone": "Asia/Hong_Kong"
}
}
I want to extract all school names from education field. Any ideas?
Working with JSON objects is similar to working with XML, except that parsing or encoding a JSON object is much easier.
Once this string is retrieved, simply call JSON.parse() on the string to get a native object representation.
var data = JSON.parse(json);
Browser.msgBox(data.info.os);
Other sample code is at https://developers.google.com/apps-script/advanced/bigquery#run_query