Cannot pass a string array from external data file postman automation scripts - arrays

I'm trying to pass a string array in postman- post request
postman request- body
{
"fruits":[{{fruits}}],
}
postman- test
var fruits=["mango","apple","orange"]
for (let i = 0; i < 3; i++) {
fruits.push(jsonData.fruits.toString());
}
pm.globals.set("fruits", fruits);
Then set fruits as global variables
Then run the API through the collection runner with the external data file. Then check the response body and I got this
got a 404 error
If anyone can let me know how to pass a array as a string in postman. When we pass a string array it will defined as a ascii value. So this issue has happened. So please guide me through this.

First, if you want to save an array as a variable, remember to stringify this.
let fruits=["mango","apple","orange"]
pm.globals.set("fruits", JSON.stringify(fruits));
Second, you don't need to add [ ] in request body, just put the variable
{
"fruits": {{fruits}}
}
Result:
{
"fruits": ["mango","apple","orange"]
}

Related

How do I append elements to a global array (in a for loop) in Swift?

I have an empty global array. The only simple thing I want to do is add an element to this array. It seems in swift this seemingly simple task is proving to be difficult. I am just left with an empty array and nothing is appending to my global array.
I can see that it prints out values in the for loop. So the values are actually there.
This is some stuff I have declared globally (Yes, I know global variables are bad but I will sort that out later):
struct HouseDetails: Decodable {
let median_price: String
let sale_year: String
let transaction_count: String
let type: String
}
var hsArray: [HouseDetails] = []
and in the viewDidLoad() function I have the data which I am storing in local variable "houses". When I loop through the array it prints median_price, showing that the values are there.
However when I do hsArray.append(h) it seems to do nothing.
let jsonUrlString = "https://data.melbourne.vic.gov.au/resource/i8px-csib.json"
guard let url = URL(string: jsonUrlString)
else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let houses = try JSONDecoder().decode([HouseDetails].self, from: data)
for h in houses {
hsArray.append(h)
print(h.median_price)
}
}
catch let jsonErr {
print("Error with json serialization", jsonErr)
}
}.resume()
Thank you for any help. In other languages I am used to being able to append an element to the end of an existing array, so I am sure it is just a small error.
Firstly, why don't you simply do
hsArray.append(contentsOf: houses)
instead of all that for loop
for h in houses {
hsArray.append(h)
print(h.median_price)
}
The issue might be the time at which you are using hsArray. See if the response is received after you use hsArray.

How to marshal an empty struct as an empty array

I'm not sure if the title accurately explains what I'm looking to do so I'll try to give as many details as I can.
I have a struct with nested structs that I am marshalling and sending out to an API. There are some requests that require my lowest level struct to be empty and I need its parent parameter to equal an empty array instead of null. If I use omitempty on the parameter, it will completely remove it from my request and the request will fail. If I use omitempty on the parameter's parameters, it causes the value to be null and the request will fail.
Here are the structs I am using for the request:
// SubscribeRequest is the top level wrapper for ICWS request bodies
SubscribeRequest struct {
ClientStateIsFresh bool `json:"clientStateIsFresh"`
StatisticKeys []StatisticKey `json:"statisticKeys"`
}
// StatisticKey is a value we want to pull from ICWS reporting
StatisticKey struct {
StatisticIdentifier string `json:"statisticIdentifier"`
ParameterValueItems []Parameter `json:"parameterValueItems"`
}
// Parameter is a filter applied when pulling statistics
Parameter struct {
ParameterTypeID string `json:"parameterTypeId"`
Value string `json:"value"`
}
And I need the marshalled JSON to look like this:
{
"clientStateIsFresh":true,
"statisticKeys":
[
{
"statisticIdentifier":"inin.system.interaction:ActiveCalls",
"parameterValueItems":
[
]
}
]
}
If I have anything other than this, the request fails. I don't get any errors, but it doesn't return any usable data. Any suggestions on how to accomplish this?
*Note: I did try using []*Parameter instead of []Parameter, but it gave me the same result.
If you want an empty array, you have to provide an empty slice.
StatisticKey{
StatisticIdentifier: "id.string",
ParameterValueItems: []Parameter{},
}

Swift 2 - How can I run a code after an asynchronous method?

I am using the following asynchronous method to get data from Firebase, ref is just my database url. It's working perfectly but I want to run the for loop after the data has been loaded. Because it's an asynchronies method, it starts to get the data from the database and immediately goes to the for loop. Anyway I can get it to wait till the data is downloaded then run the for loop? Please help! :-)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value.objectForKey("Table")!)
s = snapshot.value.objectForKey("items:")! as! String
Str = s.componentsSeparatedByString(",")
})
for(var i = 0 ; i < Str.count ; i++){
print(Str[i])
}
Your code should probably look something like this:
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value.objectForKey("Table")!)
s = snapshot.value.objectForKey("items:")! as! String
Str = s.componentsSeparatedByString(",")
for part in Str {
print(part)
}
})
I also changed your loop to make it compatible with the next version of Swift.

JSON encode array of objects

I have an array of objects like so:
[{}, {}, {}]
I need to pass this array via Socket.io. Socket.io converts the array into JSON and I keep getting the circular structure to JSON error.
Heres my current code:
for (var i = 0; i < 5; i++) {
num = randRange(0, cards[type].length);
playerCards.push(cards[type][num]);
}
socket.emit('updateCards', playerCards);
Does anyone know a way around this?
Thanks
You would see the same error if you tried to do the following:
for (var i = 0; i < 5; i++) {
num = randRange(0, cards[type].length);
playerCards.push(cards[type][num]);
JSON.stringify(cards[type][num])
}
//socket.emit('updateCards', playerCards);
The tag attribute is likely the culprit. In order for the JSON serializer to work you cannot have any circular references in the object being serialized. One option would be to pull out the information needed from the tag object and create a custom object instead.

JSON: How do I select an array inside another array?

I have the current JSON file:
[{"id":"1","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]},
[{"id":"2","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]}
How do I select the array with ID 1 and list every 'img_id' inside it, without repeating it for the other array?
edit 1:
I am trying to parse it like this but this code is erroneous:
$("#button").click(function() {
$.getJSON("../path/to/json", function(data) {
$.each(data[0].images.img_id, function(i,data){
var new_data ="<p src='path/to/folder/"+images.img_id+"'></p>";
$(new_data).appendTo("#htmlTag");
});
}); return false;
});
Much appreciated.
You have an array of objects, where each object contains another array of objects. I'm assuming the JSON structure you are using is:
var a = [{"id":"1","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]},
{"id":"2","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]}];
I'm also assuming you are using JavaScript.
PostEdit:
Your code is fairly close, I believe what I have below should work:
$("#button").click(function() {
$.getJSON("../path/to/json", function(data) {
$.each(data[0].images, function(i,data){
var new_data ="<p src='path/to/folder/" + data.img_id + "'></p>";
$(new_data).appendTo("#htmlTag");
});
});
return false;
});
All I did was change the first parameter to your each call from: data[0].images.img_id to: data[0].images. Also, I changed the declaration of new_data from:
var new_data ="<p src='path/to/folder/"+images.img_id+"'></p>";
to:
var new_data ="<p src='path/to/folder/"+data.img_id+"'></p>";
Note that the parameter "data" in the each callback function is simply the element in the array, while "i" is the index of that element in the array. Therefore, data is an object which looks like this:
{"img_id":1}
So, you can get the ID via data.img_id. Hope this helps.
I think you're talking about references. I don't think they are possible in JSON. In case you strictly need them and still want the readable serialization of your objects - I'd suggest you to look into YAML
I think there is a typo in your JSON...it seems like a bracket is missing at the end, and one has been added at the start of line 2. But, assuming you meant this (and are using Javascript):
var myJson = [{"id":"1","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]},
{"id":"2","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]}];
then you can access whatever you need just like a nested Javascript object. If you wanted to only access the object with ID equal to 1, and order is not guaranteed, you would have to iterate:
for(var i = 0; i < myJson.length; i++){
if(myJson[i].id === "1"){
var imgs = myJson[i].images;
for(var j = 0; j < imgs.length; j++){
//do what you want with imgs[j].img_id
}
}
}

Resources