postman: Is there any way to figure out the data file type/name during execution? - postman

I need to create pre-request scripts that adapt behavior based on whether data is sourced via json or csv files.
Is there any runtime mechanism to determine the data file type or the name of the data file?
Something that helps me do the following,
if (data.fileType === "json") {
//data interpretation as per json hierarchy
} else {
//data interpretation as per csv structure
}
Here, what can I use to replace data.fileType?
Or is it possible to figure out data.fileName?

You can try parsing data as json.
var parsedData;
try {
parsedData = JSON.parse(data); // Will throw an error if data not JSON
// Your logic to parse data as JSON goes here
} catch (e) {
parsedData = data; // data is not JSON, check for CSV
// Your logic to parse as CSV goes here
}

Related

Json http respone, if else statement

I CANNOT ALTER THE JSON RESPONSE, SHOWN BELOW.
I want to be able to detect when the POST message was successfully entered into the database. When the data is successfully entered the response is:
{"status":"success","message":"successfully inserted"}
I want to then use an if-else statement in Arduino to detect when this is received from the server. So my code will look something like this:
while(client.available())
{
String line = client.readStringUntil('\n');
Serial.print(line);
Serial.print("\n");
if(line == "{"status":"success","message":"successfully inserted"}")
{
update_var++;
Serial.print("SUCCESSFUL");
break;
}
else
{
Serial.print("UNSUCCESSFUL");
}
}
However, a problem immediately arises in the if statement. This is due to the quotation marks also appearing in the string. How do I use an if-else statement when receiving JSON response?
This just requires escaping if you're testing literally:
if (line == "{\"status\":\"success\",\"message\":\"successfully inserted\"}")
Keep in mind this could just as easily have the keys swapped, there's no guarantee they'll be in that order. This is why using a proper JSON parser is imperative.
I recommend using a JSON library for parsing JSON but if that's not an option, I recommend comparing your String with a raw string literal (option 6 in the link) to avoid escaping of any character:
if(line == R"aw({"status":"success","message":"successfully inserted"})aw") {
// ...
}

How to parse .txt file and get data from it in swift 3

I have a text file, I want to parse the data from it, I want some data from that text file as, city name, max temp, year,
here is link of text file enter link description here
I want uk, max temp, year, and temp from this url. How can i parse it and get data from this text file. e.g, UK,Max temp,1910,JAN,5.4. Is this possible to parse and get data from this text file?
Any suggestion will be appreciated.
In Swift 3.0 you can parse txt file like this:
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
//reading
do {
let text2 = try String(contentsOf: path, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
Note: if you want to read some static data, my recommendation would always be a JSON file saved locally.
EDIT:
One more way, maybe easier approach:
let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)
EDIT:
This is API example for your need in JSON

how to save a xml list from response to a csv file in JMeter

one of my tests uses a Loop Controller, CSV Data Set Config and an If Controller to iterate through a csv list to do one request with several parameters defined in an csv file.
I want to change this testcase to use a list of parameters that i get from an GET response in an xml format.
for example using this xml list: http://www.w3schools.com/xml/cd_catalog.xml
now i want to iterate through all < TITLE > values.
i tried to save the response with the 'Save Responses to a file' Listener and then use a BeanShell Listener to read the file and transform it to a csv list which contains only the < TITLE > values. but i'm not sure how to to this transformation part in the BeanShell Listener.
import org.apache.jmeter.services.FileServer;
import org.apache.commons.io.FileUtils;
File xmlFile = new File(FileServer.getFileServer().getBaseDir()+"/resources/data/csv/response1.xml", "UTF-8");
String fileData = FileUtils.readFileToString(xmlFile);
fileData = fileData.replaceAll("<?xml version="1.0" encoding="UTF-8"?>", "");
fileData = fileData.replaceAll("<CATALOG>", "");
//...
FileUtils.writeStringToFile(xmlFile, fileData);
/*
f = new FileOutputStream(FileServer.getFileServer().getBaseDir()+"/resources/data/csv/parameterlist.csv", true);
p = new PrintStream(f);
p.println(fileData);
p.close();
f.close();
*/
there must be some solution using regex, xpath or XSL transformation on all < TITLE > elements or is there an easier way that i didn't thought of?
found a different and easier method that works for my purpose:
Get Request to get the xml list.
add XPath Extractor
Reference Name: 'titles'
XPAth query: '//title'
ForEach Controller
Input variable prefix: 'titles'
Output variable name: 'title'

TideSDK How to save a cookie's information to be accessed in different file?

I am trying to use TideSDK's Ti.Network to set the name and value of my cookie.
But how do I get this cookie's value from my other pages?
var httpcli;
httpcli = Ti.Network.createHTTPCookie();
httpcli.setName(cname); //cname is my cookie name
httpcli.setValue(cvalue); //cvalue is the value that I am going to give my cookie
alert("COOKIE value is: "+httpcli.getValue());
How would I retrieve this cookie value from my next page? Thank you in advance!
ok, there are a lot of ways to create storage content on tidesdk. cookies could be one of them, but not necessary mandatory.
In my personal oppinion, cookies are too limited to store information, so I suggest you to store user information in a JSON File, so you can store from single pieces of information to large structures (depending of the project). Supposing you have a project in which the client have to store the app configuration like 'preferred path' to store files or saving strings (such first name, last name) you can use Ti.FileSystem to store and read such information.:
in the following example, I use jQuery to read a stored json string in a file:
File Contents (conf.json):
{
"fname" : "erick",
"lname" : "rodriguez",
"customFolder" : "c:\\myApp\\userConfig\\"
}
Note : For some reason, Tidesdk cannot parse a json structure like because it interprets conf.json as a textfile, so the parsing will work if you remove all the tabs and spaces:
{"fname":"erick","lname":"rodriguez","customFolder":"c:\\myApp\\userConfig\\"}
now let's read it.... (myappfolder is the path of your storage folder)
readfi = Ti.Filesystem.getFile(myappfolder,"conf.json");
Stream = Ti.Filesystem.getFileStream(readfi);
Stream.open(Ti.Filesystem.MODE_READ);
contents = Stream.read();
contents = JSON.parse(contents.toString);
console.log(contents);
now let's store it....
function saveFile(pathToFile) {
var readfi,Stream,contents;
readfi = Ti.Filesystem.getFile(pathToFile);
Stream = Ti.Filesystem.getFileStream(readfi);
Stream.open(Ti.Filesystem.MODE_READ);
contents = Stream.read();
return contents.toString();
};
//if a JSON var is defined into js, there is no problem
var jsonObject = {
"fname":"joe",
"lname":"doe",
"customFolder" : "c:\\joe\\folder\\"
}
var file = pathToMyAppStorage + "\\" + "conf.json";
var saved = writeTextFile(file,JSON.stringify(jsonObject));
console.log(saved);

How do I use RegEx to insert into a JSON response?

I'm using JSON for a web application I'm developing. But for various reasons I need to create "objects" that are already defined on the client script based on the JSON response of a service call. For this I would like to use a regex expression in order to insert the "new" statements into the JSON response.
function Customer(cust)
{
this.Name = null;
this.ReferencedBy = null;
this.Address = null;
if (cust != null)
{
this.Name = cust.Name;
this.ReferencedBy = cust.ReferencedBy;
this.Address = cust.Address;
}
}
The JSON response is returned by an ASP.NET AJAX Service and it contains a "__type" member that could be used to determine the object type and insert the "new" statement.
Sample JSON:
{"__type":"Customer", "ReferencedBy":{"__type":"Customer", "Name":"Rita"}, "Name":"Joseph", "Address":"123 {drive}"}
The resulting string would look like this:
new Customer({"ReferencedBy":new Customer({"Name":"Rita"}), "Name":Joseph", "Address":"123 {drive}"})
I got this so far but it doesn't work right with the ReferencedBy member.
match:
({"__type":"Customer",)(.*?})
replace:
new Customer({$2})
Hmmm why don't you try to make a simplier way to do it? e.g.:
var myJSON = {"__type":"Customer", "ReferencedBy":{"__type":"Customer", "Name":"Rita"}, "Name":"Joseph", "Address":"123 {drive}"};
after check the type: myJSON.__type, and if it is customer, then:
new Customer({"ReferencedBy":new Customer({"Name":myJSON.ReferencedBy.Name}), "Name":myJSON.Name, "Address":myJSON.Address });
It is because you already have a defined data structure, it is not neccessary to use regex to match pattern & extract data.