How to wrap Datamapper to_json response in a object-key hash - json

I'm working with a json parser that requires my response to be wrapped in an object-key hash. When I use DataMapper's .to_json method(datamapper/dm-serializer) the repsone I get is correct
get '/plane/all' do
#plane = Plane.all(:order => :id.desc).to_json(:relationships => {:pilots => {}, :passengers => {}, :cabin => {}})
#plane
end
The response in JSON
[{"id":2,"name":"Plane 2","picture_url":"https://s3.amazonaws.com","pilots":[{"pilot_id":2,"header":"Bruce Wayne","details":"Bruce loves his batwing that flies at an average speed of 200 mph","picture_url":"www.marvel.com","plane_id":2}],"passengers":[{"passenger_id":2,"name":"Passenger 2","details":"These are the details for passenger 2","picture_url":"www.toobar.com/","plane_id":2}],"cabin":[{"cabin_id":2,"details":"Great Details for has been put in this cabin","picture_url":"www.seatingchart.com","video_link":"www.skyview.com","passenger_passenger_id":2}]},{"id":1,"name":"Plane 1","picture_url":"https://s3.amazonaws.com","pilots":[{"pilot_id":1,"header":"Jack Smith","details":"Jack Smith description","picture_url":"https://www.foobar.com","plane_id":1}],"passengers":[{"passenger_id":1,"name":"Passenger 1","details":"Passenger 1 details","picture_url":"www.toobar.com/","passenger_id":1}],"cabin":[{"cabin_id":1,"details":"Flight details","picture_url":"www.seatingchart.com","video_link":"www.skyview.com","passenger_passenger_id":1}]}]
To wrap this response as a key I used the 'json' gem which has it's own to_json method
get '/plane/all' do
#plane = Plane.all(:order => :id.desc).to_json(:relationships => {:pilots => {}, :passengers => {}, :cabin => {}})
{ "planes" => #plane }.to_json
end
Here is the response
{"planes":"[{\"id\":2,\"name\":\"Plane 2\",\"picture_url\":\"https://s3.amazonaws.com\",\"pilots\":[{\"pilot_id\":2,\"header\":\"Bruce Wayne\",\"details\":\"Bruce loves his batwing that flies at an average speed of 200 mph\",\"picture_url\":\"www.marvel.com\",\"plane_id\":2}],\"passengers\":[{\"passenger_id\":2,\"name\":\"Passenger 2\",\"details\":\"These are the details for passenger 2\",\"picture_url\":\"www.toobar.com/\",\"plane_id\":2}],\"cabin\":[{\"cabin_id\":2,\"details\":\"Great Details for has been put in this cabin\",\"picture_url\":\"www.seatingchart.com\",\"video_link\":\"www.skyview.com\",\"passenger_passenger_id\":2}]},{\"id\":1,\"name\":\"Plane 1\",\"picture_url\":\"https://s3.amazonaws.com\",\"pilots\":[{\"pilot_id\":1,\"header\":\"Jack Smith\",\"details\":\"Jack Smith description\",\"picture_url\":\"https://www.foobar.com\",\"plane_id\":1}],\"passengers\":[{\"passenger_id\":1,\"name\":\"Passenger 1\",\"details\":\"Passenger 1 details\",\"picture_url\":\"www.toobar.com/\",\"plane_id\":1}],\"cabin\":[{\"cabin_id\":1,\"details\":\"Flight details\",\"picture_url\":\"www.seatingchart.com\",\"video_link\":\"www.skyview.com\",\"passenger_passenger_id\":1}]}]"}
Long story short, the JSON response I get has backslashes in it and JSON parser I'm using states it's only one object instead of the two I had previously.
Anyone who can help me out, it would be greatly appreciated.

Here is my workaround. If there is no view, then no need to use an instance variable.
def '/plane/all' do
planes = Plane.all(:order => :id.desc).to_json(:relationships => {:pilots => {}, :passengers => {}, :cabin => {}})
{ "planes" => JSON.parse(planes) }.to_json
end

Related

Pull data from wordpress database - unknown format

I need help pulling data from the field with unknown format of data structure. I am using a wordpress quiz plugin and i want to pull data from its backend table.
Data stored in answer_data is:
a:4:{
i:0;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:17:"Kieran Trippier ";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:0;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}
i:1;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:11:"Hugo Lloris";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:0;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}
i:2;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:14:"Moussa Dembele";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:0;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}
i:3;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:14:"Jan Vertonghen";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:1;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}
}
while looking at the structure of the table, data type of answer_data is longtext but has utf8_general_ci alongside it. I dont know what this means.
From this data i want to pull, quiz answers i.e.Kieran Trippier,Hugo Lloris,Moussa Dembele and Jan Vertonghen.
Any help or hint will be very much appreciated.
EDIT 1:
Array (
[0] => WpProQuiz_Model_AnswerTypes Object ( [_answer:protected] => Kieran Trippier [_html:protected] => [_points:protected] => 1 [_correct:protected] => [_sortString:protected] => [_sortStringHtml:protected] => [_mapper:protected] => )
[1] => WpProQuiz_Model_AnswerTypes Object ( [_answer:protected] => Hugo Lloris [_html:protected] => [_points:protected] => 1 [_correct:protected] => [_sortString:protected] => [_sortStringHtml:protected] => [_mapper:protected] => )
[2] => WpProQuiz_Model_AnswerTypes Object ( [_answer:protected] => Moussa Dembele [_html:protected] => [_points:protected] => 1 [_correct:protected] => [_sortString:protected] => [_sortStringHtml:protected] => [_mapper:protected] => )
[3] => WpProQuiz_Model_AnswerTypes Object ( [_answer:protected] => Jan Vertonghen [_html:protected] => [_points:protected] => 1 [_correct:protected] => 1 [_sortString:protected] => [_sortStringHtml:protected] => [_mapper:protected] => ) )
how to get values from this array?
That is some form of serialization. It seems to be an array a of 4 elements, each of which is further structure. The plugin understands; you probably don't need to understand it.
utf8_general_ci is the "Collation" to be used for comparing the LONGTEXT strings. It implies CHARACTER SET utf8, which is the 3-byte subset of UTF-8 (aka, MySQL's utf8mb4). This allows you to include characters from most languages around the world.
One would hope that the plugin provides a way to dissect this structure, rather than leaving you guessing. Furthermore, the plugin could change the structure without notice.
Here's the hint: See PHP's serialize() and unserialize().
Using the unserialized result:
$foo seems to be an array of 'objects' of class WpProQuiz_Model_AnswerTypes. One of the 'properties' of that object seems to be $_answer. So, see if this gives you the list of answers:
foreach($foo as $obj) {
echo $obj->_answer, "\n";
}
Or, to grab the answers into an array $answers:
$answers = array();
foreach($foo as $obj) {
$answers[] = $obj->_answer;
}

Inserting JSON to DB Using Model in Laravel

I'm trying to use the model create option and this is my array:
$result = array(
'match_id' => $input['id'],
'score' => $input['score'],
'result' => $input['result'],
'headline' => NULL,
'article' => $input['report'],
'tries' => $input['try'],
'try_amount' => $input['tryquant'],
'conversions' => $input['conv'],
'conv_amount' => $input['convquant'],
'penalties' => $input['pens'],
'pen_amount' => $input['penquant'],
'dropgoals' => $input['dgs'],
'dg_amount' => $input['dgquant']
);
Result::create($result);
The contents of some of these are arrays themselves. eg:
$input['penquant'] = [
"4"
]
When I run my code, it saves the data to the DB simply as Array and throws up the following error:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
Can someone tell me what I'm doing wrong and how to fix it?
Shouldn't have rushed, forgot to use json_encode.
The best is to use mutators and accessors in your model.
example of mutator
// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it
// into the database
public function setPenAmountAttribute($value)
{
$this->attributes['pen_amount'] = serialize($value);
}
example of an accessor is
// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
return unserialize($value);
}
You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.

Laravel Response::json not returning JSON properly?

Routes registered in app/routes.php
Route::resource('users', 'UsersController',
array('except' => array('new', 'update')));
Route::post('users/authenticate', array('as' => 'authenticate', 'uses' => 'UsersController#authenticate'));
Route::get('users/is_authenticated', array('as' => 'authenticated', 'uses' => 'UsersController#is_authenticated'));
The method is_authenticated is not returning JSON, but when I put the Response::json() in the index method it returns the JSON schema.
Here is my is_authenticated method:
public function is_authenticated()
{
return Response::json(['authenticated' => Auth::check()]);
}
What's going wrong here? I ran php artisan routes and it returns this for the route:
GET|HEAD api/users/is_authenticated | authenticated | UsersController#is_authenticated
I don't get a 404 Not Found when visiting the page, but there is no content. What's the problem?
Edit: routes are prefixed with api
The problem is that your first route is activated when calling users/is_authenticated. The order of the routes is important in Laravel, as the first matching route is executed. You can just change the order of your routes to make the route users/is_authenticated available, like so:
Route::post('users/authenticate', array('as' => 'authenticate', 'uses' => 'UsersController#authenticate'));
Route::get('users/is_authenticated', array('as' => 'authenticated', 'uses' => 'UsersController#is_authenticated'));
Route::resource('users', 'UsersController', array('except' => array('new', 'update')));

REST and passing authentication token

I'm writing my first REST program and I'm struggling with passing the session token. Also I have looked in several forums for similar issues questions, but with no luck.
So I have the following piece of Ruby chunk code (not the whole script):
require 'rest-client'
require 'json'
headers_lbvserver = {
'Content-Type' => application/vnd.com.citrix.netscaler.lbvserver+json',
'accept' => :json
}
add_lbvserver = RestClient::Request.execute(
:method => :post,
:url => url_lbvserver,
:headers => headers_lbvserver,
:payload => payload_lbvserver,
:cookie => {'NITRO_AUTH_TOKEN=' => token_login}
)
So I have already received the token from a previous REST post, but I can't passing it trough when i maken my second call to the object. It comes with the following error: 400 Bad Request (RestClient::BadRequest)
After looking through the docs of RestClient, it looks like you are declaring your cookie incorrectly. You don't need to have an equal sign after the cookie name:
:cookie => {'NITRO_AUTH_TOKEN=' => token_login}
should be
:cookie => {'NITRO_AUTH_TOKEN' => token_login}

Extract data from array in DB (rails)

I am trying to extract some data from an array with the following syntax:
#entries_from_db = XrEntry.find(:all, :conditions => [:FeedURI => uri ], :select => 'json')
The :FeedURI is the record that contains an array with uri's ["123456", "23345", "4453"]
The uri is the variable wich contains the current uri.
The statement I'm trying to make is 'select JSON from XrEntry where FeedURI contains uri'
Im stuck on the part to access the array and always get several error msg's when I'm trying different code.
Does anyone has an idea?
Thanks!
I solved it with this syntax
#entries_from_db = XrEntry.find(:all, :conditions => ["FeedURI like ?", "%#{uri}%"] , :select => 'json')
the "%#{your_rails_variable}%" is needed to read in an array
You seem to have switched the condition syntax. you chould start with the db attribute and then the variable.
#entries_from_db = XrEntry.find(:all,
:conditions => { :uri => FeedURI },
:select => 'json')
That will return an array of XrEntry objects with only the json attribute present. To get an array of only the json data you could map it like this:
#json_array = #entries_from_db.map(&:json)