How i can set collection variables from response? - parsing

I have some endpoint and when I do this:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable ("user_id", jsonData.data.id);
variable user_id saved to Enviroment variables, but when I do this:
var jsonData = JSON.parse(responseBody);
pm.collectionVariables.set("user_id", jsonData.data.id);
variable user_id didn't save to collection variables. What I do incorrect?
P.S. response looks like this:
{
"result": true,
"data": {
"id": "***",
"name": "***"
},
"message": ""
}
I want set collection variables from response

Related

Authorize.net payment gateway Charge a Credit Card API for iOS swift

hello everyone as i am using payment gateway charge credit api but i am getting error while passing json object to api.and here my original JSON object which pass to charge credit api.
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "XXXXXX",
"transactionKey": "XXXXXXXX"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
}
}
}
}
this is original json request
but in iOS while making JSON we get below JSON object and sequence of JSON object are change that's why we getting error from api.
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "XXXXXX",
"transactionKey": "XXXXXXX"
},
"refId": "123456",
"transactionRequest": {
"amount": "5",
"payment": {
"creditCard": {
"cardCode": "999",
"cardNumber": "5424000000000015",
"expirationDate": "2020-12"
}
},
"transactionType": "authCaptureTransaction"
}
}
}
after passing this JSON object to API, we will get bellow error
{
"messages": {
"resultCode": "Error",
"message": [
{
"code": "E00003",
"text": "The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'amount' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'transactionType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."
}
]
}
}
here is my code for creating JSON object in app
var dict = Dictionary<String, Any>()
dict=[
"merchantAuthentication": [
"name": "xxxxxxx",
"transactionKey": "xxxxxxx"
],
"refId": "5656",
"transactionRequest": [
"transactionType": "authCaptureTransaction",
"amount": "55",
"payment": [
"creditCard": [
"cardNumber": "4111111111111111",
"expirationDate": "2020-12",
"cardCode": "999"
]
]
]
]
after print this JSON sequence are changed
Have you read the documentation? It's very clear from the linked page that what you're running into is a side effect of their translation of JSON elements to XML elements in the backend, specifically around the ordering of parameters in your JSON request:
A Note Regarding JSON Support
The Authorize.Net API, which is not
based on REST, offers JSON support through a translation of JSON
elements to XML elements. While JSON does not typically require a set
order to the elements in an object, XML requires strict ordering.
Developers using the Authorize.Net API should force the ordering of
elements to match this API Reference.
Their examples below this block also show that their transactionType parameters appear as the first attribute in the transactionRequest object. Tl;dr - move your transactionType parameter up in your transactionRequest object:
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "XXXXXX",
"transactionKey": "XXXXXXX"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardCode": "999",
"cardNumber": "5424000000000015",
"expirationDate": "2020-12"
}
}
}
}
}
please try with following code.
let merchantSub = ["name": "XXXXXX",
"transactionKey": "XXXXXXX"]
let childCreditCard = ["cardCode": "999",
"cardNumber": "5424000000000015",
"expirationDate": "2020-12"]
let creditCard = ["creditCard":childCreditCard]
let transactionRequest = ["amount": "",
"payment":creditCard,
"transactionType":""] as [String : Any]
let merchantAuthentication = ["merchantAuthentication" :merchantSub,
"refId" : "123456",
"transactionRequest":transactionRequest] as [String : Any]
let param = ["createTransactionRequest" : merchantAuthentication]
if let data = try? JSONSerialization.data(withJSONObject: param, options: .prettyPrinted),
let str = String(data: data, encoding: .utf8) {
print(str)
}
However I recommend to use class but for initial level do like this.

Set values from response to environmental variable array

I have a Postman POST request, where response body looks like this:
{
"data": [
{
"object": "Answer",
"id": 507,
...
},
{
"object": "Answer",
"id": 208,
...
}
],...
In following DEL request this ids should be used in body as array:
{
"ids": [id1, id2]
}
How can i get these ids from response and store it as environment variable array [id1, id2] so then it could be used like "ids": {{answer_ids_array}} ?
To capture the id values as an array and set in an environment variable you could add something like this to the Tests tab of the first request:
let myArray = []
_.each(pm.response.json().data, (item) => {
myArray.push(item.id)
})
pm.environment.set("idArray", myArray)
To use the array in the request body, you would need to add this to the Pre-request script to transform to saved string back into an array:
pm.environment.set("ids", JSON.stringify(pm.environment.get("idArray")))
Your request body would then be something like this:
{
"ids": {{ids}}
}

Accessing Values in Deeply Nested Array - Ruby on Rails

I am using an API call which returns a JSON response. I want to access the data inside the response so I can create some nice display cards showing the info and pictures. Here is a snippet from the response, the response property is populated with about 20 objects I'll include just two for brevity:
{
"success": true,
"message": "",
"result": [
{
"MarketCurrency": "LTC",
"BaseCurrency": "BTC",
"MarketCurrencyLong": "Litecoin",
"BaseCurrencyLong": "Bitcoin",
"MinTradeSize": 1e-8,
"MarketName": "BTC-LTC",
"IsActive": true,
"Created": "2014-02-13T00:00:00",
"Notice": null,
"IsSponsored": null,
"LogoUrl": "https://i.imgur.com/R29q3dD.png"
},
{
"MarketCurrency": "DOGE",
"BaseCurrency": "BTC",
"MarketCurrencyLong": "Dogecoin",
"BaseCurrencyLong": "Bitcoin",
"MinTradeSize": 1e-8,
"MarketName": "BTC-DOGE",
"IsActive": true,
"Created": "2014-02-13T00:00:00",
"Notice": null,
"IsSponsored": null,
"LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
},
In my Rails controller I'm using JSON.parse and I'm trying to turn it into an object with the Open struct option:
#markets = JSON.parse(markets.to_json, object_class: OpenStruct)
In my view I'll do this <%=#markets.class%> and it shows Array and not object. So I try this <%=#markets.size%> and it shows 1. If I do <%=#markets[0]['success']%> I would expect it to return true but it returns 'success'. So, I'm not understanding why the ostruct library isn't working like I would expect or how I can get to the objects stored in the result array. Any help is greatly appreciated!
You already have a JSON response, isn't needed to use to_json again, try just parsing that object, and then use the dot . to access its fields, as an OpenStruct object now then you can access them as methods:
require 'json'
a = '{
"success": true,
"message": "",
"result": [{
"MarketCurrency": "LTC",
"BaseCurrency": "BTC",
"MarketCurrencyLong": "Litecoin",
"BaseCurrencyLong": "Bitcoin",
"MinTradeSize": 1e-8,
"MarketName": "BTC-LTC",
"IsActive": true,
"Created": "2014-02-13T00:00:00",
"Notice": null,
"IsSponsored": null,
"LogoUrl": "https://i.imgur.com/R29q3dD.png"
}, {
"MarketCurrency": "DOGE",
"BaseCurrency": "BTC",
"MarketCurrencyLong": "Dogecoin",
"BaseCurrencyLong": "Bitcoin",
"MinTradeSize": 1e-8,
"MarketName": "BTC-DOGE",
"IsActive": true,
"Created": "2014-02-13T00:00:00",
"Notice": null,
"IsSponsored": null,
"LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
}]
}'
b = JSON.parse(a, object_class: OpenStruct)
p b.success
# => true
After much debugging and some assistance, I was able to get it to work. The response from the API call was an array with one item. The item was a long string of the entire dataset.
In order to get the expected behavior of "true" when calling #markets.success, I first had to
raw_markets = JSON.parse(markets.to_json)
followed by
#markets = raw_markets.map do |market|
JSON.parse(market, object_class: OpenStruct)
Note: the variable markets holds the original api call:
markets = open('url-to-api')
After this I would get #markets.success = "true" and #markets.result[0] held the first result, #markets.result[1] held the second result, and so on.

SwiftyJSON Issue

I'm using Alamofire to get data from an API. I'm using SwiftyJSON to parse the JSON response. Currently, I'm iterating through product data and want to extract product details and display them in a collection view. The issue is, I can't seem to figure out how to access each product in the array. Here's the array that's returned:
{
"1": {
"product_id": 2982493187,
"merged_status": "TRUE",
"merged": [
{
"id": 2982493187,
"title": "Waves Eclipse Tee in Black",
"handle": "waves-eclipse-tee-in-black",
"published_at": "2015-10-09T21:00:50-07:00",
"published_scope": "global",
}
]
}
},
{
"2": {
"product_id": 2982432131,
"merged_status": "TRUE",
"merged": [
{
"id": 2982432131,
"title": "Waves Eclipse Tee in Off White",
"handle": "waves-eclipse-tee-in-off-white",
"published_at": "2015-10-09T21:00:50-07:00",
"published_scope": "global",
}
]
}
}
For each of these products I want to access the product_id. I'm trying to do so like so: productArray[0]["produdct_id"].int, but it doesn't seem to work. Any ideas?
You do not have an array in your results, but a dictionary with keys of "1", "2", etc.
let product_id = result["1"]["product_id"].int
It seems that the result json is an array of dictionary, so you can access the product_id via
let product_id = result[0]["1"]["product_id"].int
Try this:
let jsonProductsArray = JSON(theRawJSONData).array
for (key, productJSON):(String, JSON) in jsonProductsArray {
print(key);
let product_id = productJSON["product_id"].int
print(product_id)
}

Output JSON array without the class name in every array element

The default way to output JSON in rails is some thing like:
Code:
render :json => friends.to_json(:only => [:username, :avatar_file_name, :id ])
Output
{"friends" :
[{"user":
{"avatar_file_name": "image1.jpg", "username": "user1", "id": 1}},
{"user":
{"avatar_file_name": "image2.jpg", "username": "user2", "id": 2}},
{"user":
{"avatar_file_name": "image3.jpg", "username": "user3", "id": 3}}
]}
But i want something like:
{"friends" :
{"user": [
{"avatar_file_name": "image1.jpg", "username": "user1", "id": 1},
{"avatar_file_name": "image2.jpg", "username": "user2", "id": 2},
{"avatar_file_name": "image3.jpg", "username": "user3", "id": 3}
]}
}
The class is specified by the array name.
Last.fm also uses this syntax see Last.fm 'API-user.getfriends'
The solution to this problem is commenting the line
ActiveRecord::Base.include_root_in_json = true
in initializers/new_rails_defaults.rb
Or setting ActiveRecord::Base.include_root_in_json to false.
You can use javascript to reformat it:
var json =
{
"friends" :
{ "user": [] }
}
var i = 0;
for ( x in friends )
{
json.friends.user[i].avatar_file_name = x.user.avatar_file_name; // add more fields.
i++;
}
Something among those lines.
JSON is normally used to represent objects in a text format.
So if you like the secon output you must change your objects.
The first output says:
there is a friends object which is a array of user, each user has some properties among which you chose to expose username, avatar_file_name, id
The second output says:
there is a friends object which contains a user object which is an array of unnamed objects, each unnamed objects has some properties...
This second output is not writable in JSON syntax.
It might be:
{"friends" :
{"user": [
["avatar_file_name", "username", "id"],
["image1.jpg", "user1", 1],
["image2.jpg", "user2", 2],
["image3.jpg", "user3", 3]
]}
}
This says:
there is a friends object which contains a user object which is an array of array (a table with field names on first row) ...

Resources