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}}
}
Related
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
Question of the day: how to encode URL to be able to pass complex data on a GET request?
# data to pass
{
"main_key": {
"other_key": {
"main_array": [{
"name": "Bob",
"nickname": "bobby"
},
{
"name": "Tom",
"nickname": "Tommy"
}
]
}
}
}
Here is the current solution I got with Postman
Here is the current Rails interpretation of such a query, which is correct.
# Rails server side
Parameters: {"main_key"=>{"other_key"=>{"main_array"=>[{"name"=>"Bob", "nickname"=>"bobby"}, {"name"=>"Tom", "nickname"=>"tommy"}]}}, "default"=>{"format"=>:json}}
Can anybody have a better way to achieve a request with such a complex nested array object?
The other solution I got is to pass JSON directly as value of a query parameter and then parse it from the controller.
**Edit: ** I can pass this json on the body of the request but as it's a GET method, it does not respect XHR requirements.
If you have jquery, you can use .param() method of it.
let myParams = {
"main_key": {
"other_key": {
"main_array": [{
"name": "Bob",
"nickname": "bobby"
},
{
"name": "Tom",
"nickname": "Tommy"
}
]
}
}
}
console.log($.param(myParams));
This will give you your desired string.
"main_key%5Bother_key%5D%5Bmain_array%5D%5B0%5D%5Bname%5D=Bob&main_key%5Bother_key%5D%5Bmain_array%5D%5B0%5D%5Bnickname%5D=bobby&main_key%5Bother_key%5D%5Bmain_array%5D%5B1%5D%5Bname%5D=Tom&main_key%5Bother_key%5D%5Bmain_array%5D%5B1%5D%5Bnickname%5D=Tommy"
I have this JSON and I am trying to send it to a Rails API from Postman:
{"object":
{
"type": "out",
"vars":
{
"x": "x",
"y": "y"
},
"values":
{
"ts": "timestamp",
"ok":
{
"total": 2,
"min": "x",
"max": "y"
},
"error":
{
"total": 2,
"error1": "first",
"error2": "second"
}
}
}
}
I need to convert this into a Hash in my model so that I can manipulate it with before_create. Here's what I came with:
object = self.to_json # => converts object to json
object = JSON.parse(object) # => converts json to hash
1st problem: I get this (id=>nil is not relevant since it will be inserted automatically in the database):
{"id"=>nil, "type"=>"out", "vars"=>{"x"=>"x", "y"=>"y"}, "values"=>{"ts"=>"timestamp", "ok"=>"{\"total\"=>2, \"min\"=>\"x\", \"max\"=>\"y\"}", "error"=>"{\"total\"=>2, \"error1\"=>\"first\", \"error2\"=>\"second\"}"}, "created_at"=>"2015-01-29T15:45:01.329Z", "updated_at"=>"2015-01-29T15:45:01.329Z"}
and when I try to manipulate object["values"]["ok"], Rails sends the error:
unexpected token at '"{\"total\"=\u003e2, \"min\"=\u003e\"x\", \"max\"=\u003e\"y\"}"'
2nd problem: I can only call object["values"], and I want to call it with a symbol, not a string object[:values].
Solved my issues using:
object = self.as_json.with_indifferent_access
# => allowing me to use a symbol key instead of a string
ok_vals = object[:values][:ok].as_json.gsub(/\=\>/, ':')
# => allowing to change json string '{"val1"=>"val1", "val2"=>"val2"}' to '{"val1":"val1", "val2":"val2"}'
ok_vals = JSON.parse(ok_vals)
# => which transform json string to hash {val1: "val1", val2: "val2"}
Feel free to make any suggestions to this code. Thanks for the help.
I'm using Grails 1.3.6. I read the following JSON into a variable ...
{
"abc": {
"attr1": "value1",
"attr2": "value2"
},
"def": {
"attr1": "value1",
"attr2": "value2"
},
"ghi": {
"attr1": "value1",
"attr2": "value2"
},
...
}
If, in my controller, I'm passed a parameter referring to one part of the JSON object ...
def section = params.section; // could be "abc", "def", 'ghi", ...e
How do I access that part of the JSON assuming the above gets stored into a Groovy variable named "myJSONObject"? Thanks, - Dave
If you used JSON.parse() to create your myJSONObject, you can just do:
def value = myJsonObject[section]
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) ...