Laravel 4 Response - json

how to return response in laravel 4 like for this example ?
"key": {
"q1": "a3",
"q2": "a2",
"q3": "a1"
}
I do simple response
$key = KeyV2::all();
return Response::json(array(
'key' => $key
), 200);
result is
"key": {
"name": "q1",
"value": "a3"
}
but I need as I have described above.
I know that when I do ALL () it returns to me in this collection does not necessarily write toArray()

You can use lists() for that:
$key = KeyV2::lists('value', 'key');
return Response::json(array(
'key' => $key
));
(And 200 is unnecessary since it is the default value)

Related

Perl what is the best way to check if an object defined, missing or null within JSON

I have a JSON file below and I want to check 3 states
Within the array "categories" I have another array "children" which is currently null
How can I do to know
if children array is null ?
if children array is defined and contain at least one data ?
if children array is completely missing from the JSON whereas I was expecting to be here
Here below the JSON file
{
"id": "Store::REZZ",
"name": "Rezz",
"categories": [
{
"id": "Category::0556",
"name": "Cinéma",
"children": []
},
{
"id": "Category::0557",
"name": "Séries",
"children": []
}
],
"images": [
{
"format": "logo",
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1920px-Google_2015_logo.svg.png",
"withTitle": false
}
],
"type": "PLAY"
}
I tried something but I can manage only the case 1. for others cases I have an "Not a Hash reference" error message
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use JSON qw( decode_json );
use JSON qw( from_json );
# JSON file
my $json_f = '/home/test';
# JSON text
my $json_text = do {
open (TOP, "<", $json_f);
local $/;
<TOP>
};
my $data = from_json($json_text);
my #tags = #{ $data->{"categories"}{"children"} };
if (#tags) {
foreach (#tags) {
say $_->{"name"};
say "1. array is ok and contains data";
}
} elsif (#tags == 0) {
say "3. array is empty";
} else {
say "2. array is missing";
}
__END__
Data::Dumper will let you visualize the perl data structure the JSON is converted to. In your example,
$VAR1 = {
'images' => [
{
'withTitle' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'url' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1920px-Google_2015_logo.svg.png',
'format' => 'logo'
}
],
'id' => 'Store::REZZ',
'name' => 'Rezz',
'categories' => [
{
'children' => [],
'id' => 'Category::0556',
'name' => "Cin\x{e9}ma"
},
{
'id' => 'Category::0557',
'name' => "S\x{e9}ries",
'children' => []
}
],
'type' => 'PLAY'
};
As you can see from this, $data->{"categories"} is an arrayref of hashrefs, not a hashref itself.
You can iterate over its elements:
foreach my $cat (#{$data->{categories}}) {
if (!exists $cat->{children}) {
# No children element
} elsif (#{$cat->{children}} == 0) {
# Empty array
} else {
# Has at least element in the array
}
}
1.if children array is null ?
if (!defined($data->{categories})) { ... }
if children array is defined and contain at least one data ?
if (defined($data->{categories}) && #{$data->{categories}} ) { ... }
if children array is completely missing from the JSON whereas I was expecting to be here
if (!exists $data->{categories}) { ... }

How to loop through a JSON object in Perl?

I'm trying to create an api using perl, the api is for a react native, when the user submits a form on the app I'll get the following object,
I'm new to perl and I'm lost trying to loop thro the object :/
{
checkboxes: [
{
id: "1",
fullname: "Name 1",
color: "red",
res: false
},
{
color: "green",
fullname: "Name 2",
id: "2",
res: false
},
{
color: "blue",
id: "3",
fullname: "Name 3",
res: false
}
]
}
my $data_decoded = decode_json($data);
I'm trying this loop, but it only prints the full object.
foreach $a (#data) {
print "value of a: $a\n";
}
You turned your JSON into a reference Perl data structure with decode_json (from somewhere, and Mojo::JSON is such a place):
use Mojo::JSON qw(decode_json);
my $data = ...;
my $data_decoded = decode_json($data);
Now you have to figure out how to access whatever you have in $data_decoded. You can look at its structure by dumping it
use Mojo::Util qw(dumper);
print dumper( $data_decoded );
You'll see that the Perl structure is the same as the JSON structure. You have a hash (JSON's Object) that has a checkboxes key that points to an array. The array elements are hashes.
Using Perl v5.24's postfix dereferencing notation, you get all of the array elements:
# uglier circumfix notation #{$data_decoded->{checkboxes}}
my #elements = $data_decoded->{checkboxes}->#*;
You might put that in a loop:
foreach my $hash ( $data_decoded->{checkboxes}->#* ) {
...
}
Now you get each hash element in $hash and you can do whatever you like with it. That part you haven't told us about yet. :)
The Perl Data Structures Cookbook (perldsc) has a lot of examples of the generation and iteration of various combinations of hash and array references.
You say that you want to do something when the value of the res key is true. In that case, you can use next to skip the items where res is false:
foreach my $hash ( $data_decoded->{checkboxes}->#* ) {
next unless $hash->{res};
say "I'm doing something when res is true";
}
Following demo code demonstrates looping through these particular data
use strict;
use warnings;
use feature 'say';
use JSON;
use Data::Dumper;
my $input = do { local $/; <DATA> };
my $data = from_json($input);
say Dumper($data);
for my $obj ( #{$data->{checkboxes}} ) {
say join(",\t", $obj->#{qw/id fullname color/});
}
__DATA__
{
"checkboxes": [
{
"id": "1",
"fullname": "Name 1",
"color": "red",
"res": false
},
{
"color": "green",
"fullname": "Name 2",
"id": "2",
"res": false
},
{
"color": "blue",
"id": "3",
"fullname": "Name 3",
"res": false
}
]
}
Output
$VAR1 = {
'checkboxes' => [
{
'res' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'color' => 'red',
'fullname' => 'Name 1',
'id' => '1'
},
{
'fullname' => 'Name 2',
'color' => 'green',
'res' => $VAR1->{'checkboxes'}[0]{'res'},
'id' => '2'
},
{
'id' => '3',
'color' => 'blue',
'res' => $VAR1->{'checkboxes'}[0]{'res'},
'fullname' => 'Name 3'
}
]
};
1, Name 1, red
2, Name 2, green
3, Name 3, blue

Yii2 kartik depend dropdown doesnt load next drop down list

I am using kartik DepDropdown widget. When I choose the region it must load all the cities from it in the particular dropdown (e.g. the one with id city_id).
In the chrome network tab I can see that the action returns the expected result json format of all the cities
{
"output": {
"40": "Велико Търново",
"41": "Горна Оряховица",
"42": "Елена",
"43": "Златарица",
"44": "Лясковец",
"45": "Павликени",
"46": "Полски Тръмбеш",
"47": "Свищов",
"48": "Стражица",
"49": "Сухиндол"
},
"selected": ""
}
But they doesn't load in the #city_id dropdown. My view looks like:
<div class="col-sm-6">
<?= $form->field($model, 'region_id')->dropDownList(Region::getAllRegions(), ['id' => 'region-dd', 'prompt'=> ' - ' . Yii::t('app', 'Region') . ' - ']); ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'city_id')->widget(DepDrop::classname(), [
'options'=>[
'id'=>'city-id'
],
'pluginOptions'=>[
'allowClear' => true,
'depends' => ['region-dd'],
'url' => Url::to(['/system-information/load-cities'])
]
]); ?>
</div>
My controller:
public function actionLoadCities()
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$region_id = $parents[0];
$out = City::getAllCities($region_id);
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
Thank you in advance!
You have to provide the name=>value pairs of the id and the text to be assigned for a single option, if you look into the DOCS you will see that you have to return the array like below
[
'out'=>[
['id'=>'<city-id>', 'name'=>'<city-name>'],
['id'=>'<city-id>', 'name'=>'<city-name>']
],
'selected'=>'<city-id>'
]
which means that the id will be provided with the index id and the text for the dropdown will be provided with the index name, and looking at the response you have provided your method getAllCities is returning the array like below
[
'id'=>'name',
'id'=>'name',
]
you didn't add the method City::getAllCities($region_id); which is returning the $out array but on the very basic level as per documentation it should look like below,
Note: Change the table and column names respectively, I assume you have the id and name columns for the cities, if you have any other column name for the city name like city_name then you must create the alias name for the city_name field in the query.
public function getAllCities($region_id){
$query = new \yii\db\Query;
$query->select('id, name')
->from('{{%city}}')
->where(['=', 'region_id', $region_id])
->limit(20);
$command = $query->createCommand();
return $command->queryAll();
}
This will return an array like below.
Array
(
[0] => Array
(
[id] => 40
[name] => Велико Търново
)
[1] => Array
(
[id] => 41
[name] => Горна Оряховица
)
[2] => Array
(
[id] => 42
[name] => Елена
)
[3] => Array
(
[id] => 43
[name] => Златарица
)
)
which will be encoded as JSON like below
[
{
"id": "40",
"name": "Велико Търново"
},
{
"id": "41",
"name": "Горна Оряховица"
},
{
"id": "42",
"name": "Елена"
},
{
"id": "43",
"name": "Златарица"
}
]
and eventually when encode by the line
echo Json::encode(['output'=>$out, 'selected'=>'']);
it will return
{
"output": [
{
"id": "40",
"name": "Велико Търново"
},
{
"id": "41",
"name": "Горна Оряховица"
},
{
"id": "42",
"name": "Елена"
},
{
"id": "43",
"name": "Златарица"
}
],
"selected": ""
}
Hope this helps.

Laravel create nested json response

How to create a nested json response in Laravel 5? For example:
"response":["status":"OK",
"data":{ "user":{"name": "Shriyansh",
"email":"some#email.com",
"contact":"1234567890",
"fcmToken":"Token#123"
},
"event":{"status":"successful",
"status_code":4
}
}
]
Create an array to hold your response like this:
$data = [
"status"=> "OK",
"data"=> [
"user" => [
"name"=> "Shriyansh",
"email"=>"some#email.com",
"contact"=>"1234567890",
"fcmToken"=>"Token#123"
],
"event"=> [
"status" => "successful",
"status_code" => 4
]
]
]
Then return your data using Laravel response method like this:
return response()->json($data, 200);
So Laravel will convert your array into json format and send it back to your client.
You should try this:
$json = json_encode(array(
"status"=>"OK",
"user" => array(
"name"=> "Shriyansh",
"email"=>"some#email.com",
"contact"=>"1234567890",
"fcmToken"=>"Token#123"
),
"event" => array(
"status" => "successful",
"status_code" => 4
)
));
You can use JSON Response to return the JSON in Laravel.
Example:
Assuming you have the required data in the $data variable,
return response()->json([
'data' => $data
],200);
where, 200 is status code. status will be added as per the status code by laravel.

Hash::Ordered versus Tie::IxHash with JSON::XS encode

I'm trying Hash::Ordered instead of Tie::IxHash, because it seems to be faster.
While Tie::IxHash is working fine, I struggle with some problems with Hash::Ordered. The point is to have the hashes ordered (which are usually random in Perl).
use Hash::Ordered;
use JSON::XS;
use Data::Dumper;
use strict;
use warnings;
my $json = JSON::XS->new;
my $oh = Hash::Ordered->new;
$oh->push('result' => { 'counter' => "123" }, 'number' => { 'num' => '55' });
my #r = $oh->as_list;
$json->pretty(1);
my $jsondata = $json->encode(\#r);
print Dumper $jsondata;
The result is odd:
[
"result",
{
"counter" : "123"
},
"number",
{
"num" : "55"
}
]
Here is the working example with Tie::IxHash, I try to get the same results with Hash::Ordered.
use Data::Dumper;
use Tie::IxHash;
use JSON::XS;
use strict;
use warnings;
my $json = JSON::XS->new;
my %h;
tie(%h, 'Tie::IxHash', result => { counter => "123" }, number => { num => '55' });
$json->pretty(1);
my $pretty_json = $json->encode(\%h);
print Dumper $pretty_json;
Output
{
"result" : {
"counter" : "123"
},
"number" : {
"num" : "55"
}
}
The object-oriented interface of Hash::Ordered is much faster that the tied interface, but some utilities (like $json->encode) require a real hash reference
The way to get the best of both worlds is to tie a hash for use with those utilities, and use tied to extract the underlying Hash::Ordered object so that you can use the faster method calls to manipulate it
This short program demonstrates. The only slow part of this code is when the hash is passed to encode to be translated to JSON. The push call doesn't use the tied interface and remains fast
use strict;
use warnings;
use Hash::Ordered;
use JSON::XS;
my $json = JSON::XS->new->pretty;
tie my %h, 'Hash::Ordered';
my $oh = tied %h;
$oh->push( result => { counter => 123 }, number => { num => 55 } );
print $json->encode(\%h), "\n";
output
{
"result" : {
"counter" : 123
},
"number" : {
"num" : 55
}
}
Use the Hash::Ordered tied interface:
my $json = JSON::XS->new;
tie my %hash, "Hash::Ordered";
$hash{'result'} = { 'counter' => "123" };
$hash{'number1'} = { 'num' => '1' };
$hash{'number2'} = { 'num' => '2' };
$hash{'number3'} = { 'num' => '3' };
$hash{'last'} = { 'num' => 'last' };
$json->pretty(1);
my $jsondata = $json->encode(\%hash);
And the JSON data you get is:
{
"result" : {
"counter" : "123"
},
"number1" : {
"num" : "1"
},
"number2" : {
"num" : "2"
},
"number3" : {
"num" : "3"
},
"last" : {
"num" : "last"
}
}
The examples above work fine, but for multidimensional hashes there is an additional step needed to keep the order.
use Hash::Ordered;
use JSON::XS;
use Data::Dumper;
use strict;
use warnings;
sub ordered_hash_ref {
tie my %hash, 'Hash::Ordered';
my $oh = tied %hash;
$oh->push(#_);
return \%hash;
};
my $json = JSON::XS->new->pretty;
tie my %h, 'Hash::Ordered';
my $oh = tied %h;
$oh->push(result => ordered_hash_ref(counter => 123, z => 5, s => 8), address => ordered_hash_ref(Vorname => 'Max',
Nachname => 'Mustermann', Strasse => 'Feldweg', Hausnummer => 45));
my $pretty = $json->encode(\%h);
print Dumper $pretty;
Output
{
"result" : {
"counter" : 123,
"z" : 5,
"s" : 8
},
"address" : {
"Vorname" : "Max",
"Nachname" : "Mustermann",
"Strasse" : "Feldweg",
"Hausnummer" : 45
}
}