I'm getting the following error when I call the code listed below it.
Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours.
My code:
var i = 0;
var tempFastingQuest = "";
var tempFastingAns = msg['OBR']['OBR.39'].toString();
while (msg['NTE'][i] != null) {
tempFastingQuest = msg['NTE'][i]['NTE.3']['NTE.3.1'].toString();
if (tempFastingQuest.contains("Yes"))
tempFastingAns = "Y";
i = i + 1
}
What am I missing here?
Assuming this is JavaScript: Strings don't have a contains() method, which the error clearly states. Maybe you are looking for the search() method: if (tempFastingQuest.search('Yes') > -1) ...
Related
I'm writing a test in postman where I want to check if a JSON return contains the Label called 'RegressieMapTest'. This is my script:
pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj = JSON.parse(objString);
for (var i = 0; i < obj.Corsa.Data.length; i++){
if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
console.log(obj.Corsa.Data[i].Label);
pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
}
}
pm.expect.fail();
})
But it doesn't quite work, every time I run this script it seems like it automatically jumps to pm.expect.fail() which is weird because 'RegressieMapTest' is inside the JSON return. Postman returns the following message:
Is the folder created correctly? | AssertionError: expect.fail()
pm.respose.json() is equalent to JSON.parse you don't have to do it again
also you can use array.find method instead of looping through it
pm.test("Is the folder created correctly?", function () {
var jsonData = pm.response.json();
pm.expect(obj.Corsa.Data.find(elem => elem.Label === "RegressieMapTest")).to.be.not.undefined
}
if array has any element with label RegressieMapTest then it will return that data elese returns undefined, so we are validating that it will not return undefined. Meaning it has the value
Your pm.expect.fail(); always runs. You want it to run only when you don't find the field. So just add a flag in your check block.
pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj = JSON.parse(objString);
var isFound = false;
for (var i = 0; i < obj.Corsa.Data.length; i++){
if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
console.log(obj.Corsa.Data[i].Label);
pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
isFound = true;
}
}
if (!isFound) {
pm.expect.fail();
}
})
I have a piece of code that I'm trying to get to work on an interface. Basically we take some fields and drop into other segments. The problem seems to be that it leaves the data where it is instead of moving it to the indexed PID segment. Also the CP variable is returning 'undefined' for some reason.
var i = msg['PID']['PID.13'].length();
var homeNum;
var netNum;
var cpNum;
while(i--)
{
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "PRN")
{
homeNum = msg['PID']['PID.13'][i]['PID.13.9'];
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "NET")
{
netNum = msg['PID']['PID.13'][i]['PID.13.4'];
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "CP")
{
cpNum = msg['PID']['PID.13'][i]['PID.13.9'];
}
msg['PID']['PID.13'][i] = "";
}
msg['PID']['PID.13'][0]['PID.13.1'] = homeNum;
msg['PID']['PID.13'][0]['PID.13.4'] = netNum;
msg['PID']['PID.13'][1]['PID.13.1'] = cpNum;
Sample HL7 msg I am using before transforms (from our test system, NOT live data)
It should resemble this instead:
|9999999999^^^test#test.com~99999999999~~~|
Any ideas/pointers on why it's not moving?
You are missing a toString() when you set the variables. A typical Mirth thing, because you get the E4X object back in the variable instead of the value you expected.
In addition to this, you should check the variables for undefined values before setting them on the new structure because otherwise you end up with "undefined" in the fields.
This is a working solution:
var i = msg['PID']['PID.13'].length();
var homeNum;
var netNum;
var cpNum;
while(i--)
{
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "PRN")
{
homeNum = msg['PID']['PID.13'][i]['PID.13.9'].toString();
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "NET")
{
netNum = msg['PID']['PID.13'][i]['PID.13.4'].toString();
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "CP")
{
cpNum = msg['PID']['PID.13'][i]['PID.13.9'].toString();
}
msg['PID']['PID.13'][i] = "";
}
if(homeNum != null) msg['PID']['PID.13'][0]['PID.13.1'] = homeNum;
if(netNum != null) msg['PID']['PID.13'][0]['PID.13.4'] = netNum;
if(cpNum != null) msg['PID']['PID.13'][1]['PID.13.1'] = cpNum;
I know lots of people think "eval is evil," but I have to accomplish something and I'm having trouble figuring out how to do it without eval().
The situation is this: an external file (I have no control over it--EDIT: but it's not user-generated. It's from a trusted source! I imagine this is important) is spitting out JavaScript for me to use. This JavaScript contains some nice JSON data (which is what I need to get), but it's flanked by ordinary JavaScript statements declaring variables and calling functions and such. It looks kinda like this:
var foo = new Object();
foo['KEY'] = {Field1: 'Value1', Field2: 'Value2'};
eval('fooFunction(foo)');
If I eval() this, I can just parse foo['KEY'] and be done with it. The only way I can think to do this without eval() is with a bunch of annoying replace()ments, which hardly seems better. Am I missing some obvious way to do this? Most of the "you don't have to use eval()" alternatives I usually see assume I have complete control over everything, but in this case I have to work around this existing code.
EDIT: I should add that this code is being obtained via an AJAX call from a proxy script (cross-domain stuff), so none of the variables are accessible. If they were, I'd obviously just be able to parse foo['KEY'] and be on my merry.
SECOND EDIT: nothing conclusive yet! I'm getting dangerously close to concluding that eval() is the way to go. Can you stomach this outcome? I'm about to give in to evil(). Somebody stop me, because it's looking like the only way.
The external code better send back valid JSON. The value in your example is not valid JSON, as the keys must be wrapped with double quote.
I came up with small pure JavaScript parser, that can handle simple invalid JSON by adding double quotes by itself. It currently won't support non string values.
function ParseRawJSON(rawCode) {
var arrCandidates = [];
var lastOpenBracketIndex = -1;
for (var i = 0; i < rawCode.length; i++) {
var curChar = rawCode.charAt(i);
if (curChar === "}") {
if (lastOpenBracketIndex >= 0) {
arrCandidates.push(rawCode.substr(lastOpenBracketIndex, i - lastOpenBracketIndex + 1));
lastOpenBracketIndex = -1;
}
} else if (curChar === "{") {
lastOpenBracketIndex = i;
}
}
var arrJsonObjects = [];
for (var i = 0; i < arrCandidates.length; i++) {
var currentJSON = null;
try {
currentJSON = JSON.parse(arrCandidates[i]);
} catch (e) {
//try fixing
var fixedCandidate = TryFixJSON(arrCandidates[i]);
if (fixedCandidate) {
try {
currentJSON = JSON.parse(fixedCandidate);
} catch (e) {
currentJSON = null;
}
}
}
if (currentJSON != null) {
var keys = [];
for (var key in currentJSON)
keys.push(key);
if (keys.length > 0)
arrJsonObjects.push(currentJSON);
}
}
return arrJsonObjects;
function Trim(s, c) {
if (c instanceof Array) {
for (var i = 0; i < c.length; i++)
s = Trim(s, c[i]);
return s;
}
if (typeof c === "undefined")
c = " ";
while (s.length > 0 && s.charAt(0) === c)
s = s.substr(1, s.length - 1);
while (s.length > 0 && s.charAt(s.length - 1) === c)
s = s.substr(0, s.length - 1);
return s;
}
function TryFixJSON(strBlock) {
if (strBlock.indexOf(":") <= 0)
return false;
strBlock = strBlock.replace("{", "").replace("}", "");
var mainParts = strBlock.split(",");
for (var i = 0; i < mainParts.length; i++) {
var currentPart = Trim(mainParts[i]);
if (currentPart.indexOf(":") <= 0)
return false;
var subParts = currentPart.split(":");
if (subParts.length !== 2)
return false;
var currentKey = Trim(subParts[0], [" ", "'", "\""]);
var currentValue = Trim(subParts[1], [" ", "'", "\""]);
if (currentKey.length === 0)
return false;
subParts[0] = "\"" + currentKey + "\"";
subParts[1] = "\"" + currentValue + "\"";
mainParts[i] = subParts.join(":");
}
return "{" + mainParts.join(", ") + "}";
}
}
This will just look for anything between { and } and try to parse as JSON. No eval, in case of failure it'll just ignore the invalid block. Success? Great, it will return plain array of the valid JSON's it found.
Usage example:
var rawCode = "var foo = new Object(); { dummy here }}} function boo() {}" +
"foo['KEY'] = { \"Field1\": \"Value1\", \"Field2\": \"Value2\"}; hello {\"foo\": \"bar\"} and it's over ";
var jsonObjects = ParseRawJSON(rawCode);
for (var i = 0; i < jsonObjects.length; i++) {
for (var key in jsonObjects[i]) {
var value = jsonObjects[i][key];
//got key and value...
}
}
Live test case, using fixed version of your sample code.
A generally safer alternative to using eval is creating a new Function and passing it the string function body. That way (unless something is explicitly acessing the window object) you won't have access to the global scope and can keep it encapsulated in the function scope.
Let's say the first two lines of your example code are the JavaScript that you'd like to evaluate, if you know the name of the variable you want to retrieve as a JSON object you can just return it at the end of the created function and then call it:
var js = "var foo = {}; foo['KEY'] = {Field1: 'Value1', Field2: 'Value2'};";
var fn = new Function(js + ';return foo;');
var result = fn();
console.log(JSON.stringify(result));
This is also what MDN suggests doing in the documentation for eval:
More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways of which the similar Function is not susceptible.
If the JSON contains just data and not functions you can use JSON.parse()
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse for more detailed info.
As the method has been placed in to the global, then you can do
window["fooFunction"](foo)
I am trying to make my first JS-based adobe air app.
But I've stuck at a point.
Here's the code which is causing the error
var RunUrl = 'http://www.lilpirate.net';
var firstRunUrl = 'http://www.netbloo.com';
var snxApp = air.EncryptedLocalStore.getItem( 'snxApp' );
var semail = snxApp.readUTFBytes( snxApp.bytesAvailable );
if( semail!='786') {
data = new air.ByteArray();
data.writeUTFBytes( '786' );
air.EncryptedLocalStore.setItem( 'snxApp', data );
var snxUrlToLoad = firstRunUrl;
}
else
var snxUrlToLoad = RunUrl;
When compiling it from adl, it throws error -
TypeError: Result of expression 'snxApp' [null] is not an object.
Help!
You are accessing properties (bytesAvailable and readUTFBytes) of snxApp without checking to make sure it exists first. If you haven't used setItem to store anything with that name yet, it will be null.
Here's an example of how it would look with an if statement:
var snxApp = ...;
var semail;
if (snxApp !== null) {
semail = snxApp.readUTFBytes( snxApp.bytesAvailable );
}
...
I have the following code in a script.
The problem is That I want to get information of scripts that starts in a specific name and are in a specific startmode.
var e = new Enumerator(GetObject("winmgmts:").InstancesOf("Win32_Service"))
var WSHShell = new ActiveXObject ("WScript.Shell");
var strPrefix = "TTTT";
for(;!e.atEnd(); e.moveNext()){
var Service = e.item();
var strName = Service.Name;
if (strName.substr (0, strPrefix.length) == strPrefix) {
if(Service.StartMode == 'mmManual') {
WScript.Echo("Yes");
}
if(e.StartMode == 'Manual') {
WScript.Echo("Yes");
}
}
}
In the above script I tried to know the start mode but it always return true.
McDowell is right, but note that you can get rid of prefix and start mode checks in your loop if you make them part of the WMI query:
SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'
Using this query, your script could look like this:
var strComputer = ".";
var oWMI = GetObject("winmgmts://" + strComputer + "/root/CIMV2");
var colServices = oWMI.ExecQuery("SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'");
var enumServices = new Enumerator(colServices);
for(; !enumServices.atEnd(); enumServices.moveNext())
{
var oService = enumServices.item();
WScript.Echo(oService.Name);
}
I'm not sure exactly what you're asking, but this...
if(Service.StartMode = 'mmManual')
...will always evaluate to true. You are missing an =. It should be:
if(Service.StartMode == 'mmManual')