HTTPI unable to pass array params - ruby

#request.url = url
#request.headers = {"Content-Type" => "application/x-www-form-urlencoded; charset=utf-8"}
#request.body = {a: "1", b: "2", c: [{d: "3"}, {e: "4"}]}
The problem is that the server side could receive params like a or b, but each value of c is null, like "c": [{"d": null}, {"e": null}]. Any help will be appreciated.
[Solved] :) The server use .net and I don't know what they did..

Related

Laravel - Convert list object to key value

I have a list object like:
"my_list":
[
{
"id": 1,
"name": A
},
{
"id": 2,
"name": B
},
]
I want to convert to key - value like:
my_list = {
1: 'A',
2: 'B'
}
How can I do that? Does anyone have solution?
Please help, thanks!
Cast it to Laravel collection and use mapWithKeys()
$keyed = collect($my_list)->mapWithKeys(function ($item) {
return [$item['id'] => $item['name']];
});
If you need to convert it to object then:
$keyed = (object)$keyed->toArray();
You can use array helper methods combines with array_combine():
(object)array_combine(Arr::pluck($my_list, 'id'), Arr::pluck($my_list, 'name'));

How to allow top-level JSON array param in Ruby Grape

I have a route with /coordinates. I want to receive a JSON Array on this route, such as:
[
{"latitude": 1, "longitude": 1},
{"latitude": 1, "longitude": 2},
{"latitude": 1, "longitude": 3}
]
How do I configure the params to parse this kind of data with grape? I don't want to give a name to the array such as { "blah": []}, I just want to read it from the request.
Here's what I'm trying to do
params do
requires :latitude, type: Float
requires :longitude, type: Float
end
post do
route = Route.create(coordinates: params)
{ id: route.id }
end

Adding hashes to hashes (Ruby)

I've tried adding hashes through #Hash.new with no success, now I am trying .merge as per the forums with limited success as well. I'm trying to add #rand(1..100) into [0] without going into the hash manually. Any ideas?
#age = Hash.new
#email = Hash.new
#age2 = rand(1..100)
people = [
{
"first_name" => "Bob",
"last_name" => "Jones",
"hobbies" => ["basketball", "chess", "phone tag"]
},
{
"first_name" => "Molly",
"last_name" => "Barker",
"hobbies" => ["programming", "reading", "jogging"]
},
{
"first_name" => "Kelly",
"last_name" => "Miller",
"hobbies" => ["cricket", "baking", "stamp collecting"]
}
]
people[0].each do |w|
people.merge({:age => rand(1..100)})
puts "array 0 is #{w}"
end
puts p people
Assuming that's your structure, you do this:
people.each do |person|
person['age'] = rand(1..100)
end
You ideally want to use symbol-style keys instead. That would mean declaring them like this:
people = [
{
first_name: "Bob",
last_name: "Jones",
...
},
...
]
That way you access them like people[0][:first_name]. Your merged in hash uses symbol keys for :age. Remember in Ruby strings and symbols are not equivalent, that is 'bob' != :bob. You should use symbols for regular structures like this, strings for more arbitrary data.

make json from params hash

I am trying to call API and pass data to it from the form in my view to controller and then call API with post method.
What I get in params is:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"kLLaVRc6kcndkfB1nkntSTzGCg95CMCT1UvEncqwLgc=",
"score_sheet"=>{
"score_sheet_master"=>{
"issue_date(1i)"=>"2014", "issue_date(2i)"=>"6", "issue_date(3i)"=>"27"},
"print_date(1i)"=>"2014", "print_date(2i)"=>"6", "print_date(3i)"=>"27", "product_id"=>"2", "pull_id"=>"2", "press_run_id"=>"1", "total_section"=>"2",
"score_sheet_sections_attributes"=>{
"0"=>{"section_name"=>"A", "total_pages"=>"2", "color_pages"=>"1", "_destroy"=>"false"},
"1"=>{"section_name"=>"B", "total_pages"=>"1", "color_pages"=>"", "_destroy"=>"false"}},
"color_pages_rated"=>"1", "bw_pages_rated"=>"2", "foreman_id"=>"", "pic_id"=>""},
"score_sheet_master"=>{
"press_id"=>"1"},
"commit"=>"Create Score sheet"}
I want this Hash to be converted into the Following JSON which APIs accept. i-e.
{
"score_sheet": {
"score_sheet_master": {
"issue_date": "2014-06-25",
"press_id": "1"
},
"print_date": "2014-06-23",
"product_id": 1,
"pull_id": 2,
"press_run_id": 1,
"total_section": 2,
"score_sheet_sections_attributes": [
{
"section_name": "A",
"total_pages": 3,
"color_pages": "2,3",
"id": 9
},
{
"section_name": "B",
"total_pages": 1,
"color_pages": "1",
"id": 10
},
{
"section_name": "C",
"total_pages": 2,
"color_pages": "2"
}
],
"pic_id": 1,
"foreman_id": 1
}
}
Some the fields in JSON might be missing or may be more than the HASH but I don't have concern with that I will handle them personally the main issue is to convert this params Hash to the required JSON. Hold On I have implemented the date conversion thing that is working fine. but don't know how to convert score_sheet_sections_attributes array format to the required format.
Oh Got it myself:
sections = []
params["score_sheet"]["score_sheet_sections_attributes"].each {|k,v| sections << v}
params["score_sheet"]["score_sheet_sections_attributes"] = sections
Which gives:
{"utf8"=>"✓", "authenticity_token"=>"kLLaVRc6kcndkfB1nkntSTzGCg95CMCT1UvEncqwLgc=", "score_sheet"=>{"score_sheet_master"=>{"issue_date(1i)"=>"2014", "issue_date(2i)"=>"6", "issue_date(3i)"=>"27"}, "print_date(1i)"=>"2014", "print_date(2i)"=>"6", "print_date(3i)"=>"27", "product_id"=>"2", "pull_id"=>"2", "press_run_id"=>"1", "total_section"=>"2", "score_sheet_sections_attributes"=>[{"section_name"=>"A", "total_pages"=>"2", "color_pages"=>"1", "_destroy"=>"false"}, {"section_name"=>"B", "total_pages"=>"1", "color_pages"=>"", "_destroy"=>"false"}], "color_pages_rated"=>"1", "bw_pages_rated"=>"2", "foreman_id"=>"", "pic_id"=>""}, "score_sheet_master"=>{"press_id"=>"1"}, "commit"=>"Create Score sheet"}
and for dates I have another logic implemented and all done.

django: Testing POST-based views with json objects

I have a django application with several views that accept json objects via POST requests. The json objects are medium-complex with a few layers of nesting, so I'm using the json library to parse raw_post_data, as shown here:
def handle_ajax_call(request):
post_json = json.loads(request.raw_post_data)
... (do stuff with json query)
Next, I want to write tests for these views. Unfortunately, I can't figure out how to pass the json object to the Client. Here's a simplest-case version of my code:
def test_ajax_call(self):
c = Client()
call_command('loadfixtures', 'temp-fixtures-1') #Custom command to populate the DB
J = {
some_info : {
attr1 : "AAAA",
attr2 : "BBBB",
list_attr : [ "x", "y", "z" ]
},
more_info : { ... },
info_list : [ 1, 22, 23, 24, 5, 26, 7 ]
}
J_string = json.dumps(J)
response = c.post('/ajax/call/', data=J_string )
When I run the test, it fails with:
AttributeError: 'str' object has no attribute 'items'
How can I pass the JSON object in the Client.post method?
The documentation seems to imply that if you pass a content_type parameter to client.post, it will treat the data value as a document and POST it directly. So try this:
response = c.post('/ajax/call/', content_type='application/json', data=J_string)

Resources