Laravel create nested json response - json

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.

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}) { ... }

Laravel Array to string conversion on multiple records

I'm trying to salve multiple records at once..
When I try to store multiple records it gives an error of array to string conversion.
This is the response I get from axios.
array:2 [
0 => array:3 [
"property_type_id" => 2
"fee_value" => "123"
"product_service_id" => 1
]
1 => array:3 [
"property_type_id" => 1
"fee_value" => "3333"
"product_service_id" => 1
]
]
$feeByPropertyType = $request->feeByPropertyType;
foreach ($feeByPropertyType as $row)
{
$data[] = [
'property_type_id' => $row['property_type_id'],
'fee_value' => $row['fee_value'],
'product_service_id' => 1
];
}
PaymentTypeProductService::insert($data);
I have tried a few other methods as well but none of them have worked so far.
Any help from the community will be greatly appreciated, on how to correct this.
You need to format your $data to be like this.
[
[
'property_type_id' => 2,
'fee_amount' => "123"
],
[
'property_type_id' => 1,
'fee_amount' => "1312"
],
]
In this case, if the data structure of the $request->feeByPropertyType data structure matches with the database tables structure, then you can simply use DB facade to insert multiple rows at once.
DB::insert($request->feeByPropertyType);

REST API: how to post a manytomany relationship with fosrestbundle

In my Symfony 4 project, I have 2 entities: Question and PossibleAnswer. A question can have many possible answers and an answer can be used in many different questions.
I want to POST a question, I use FOSRestBundle. This is how I would format the body of my request:
{
"title": "my question",
"possibleAnswers": [
{
"id": 1,
"title": "my first answer"
}
]
}
At least this is how FOSRestBundle formats the answer when I create the data directly in the database and GET the question.
But I keep getting the same error:
Validation Failed, possibleAnswers This value is not valid
I use Symfony forms to validate my POST and the fieldType I use for the possibleAnswers field of Question is an EntityType with the option multiple set to true. Maybe that's where the error comes from.
So my question is: How do I format the body of my request to add a valid possibleAnswers field ? and if I am doing it right then, which form type should I use for it to work ?
Sorry for not adding any code, the context is actually quite more complex but I'm pretty sure either the JSON Format of my field or the form type is wrong.
[edit]
here are all the form types I tried for the possibleanswers field
//->add('possibleAnswers', EntityType::class, array('data' => [], 'required' => false, 'multiple' => true, 'class' => PossibleAnswer::class))
->add('possibleAnswers', CollectionType::class, array('required' => false, 'entry_type' => EntityType::class, 'entry_options' => array('class' => PossibleAnswer::class)))
//->add('possibleAnswers', CollectionType::class, array('required' => false, 'entry_type' => PossibleAnswerType::class))
//->add('possibleAnswers', CollectionType::class, array('required' => false, 'entry_type' => PossibleAnswerType::class, 'entry_options' => array('class' => PossibleAnswer::class)))
here are all the JSON formats I tried to select the possibleanswers:
{
"title": "a postman created question",
"answerConditions": [
{
"id": 1,
"title": "already existing question",
}
]
}
{
"title": "a postman created question",
"answerConditions": [
{
"possibleanswer_id": 1
}
]
}
{
"title": "a postman created question",
"answerConditions": [
{
"id": 1
}
]
}
{
"title": "a postman created question",
"answerConditions": [
1
]
}
If you want to create the PossibleAnswer when posting the Question, you need to replace in your form the EntityType by a CollectionType.
I often use it in my POST request when I want to post the sub-object (here the PossibleAnswer) when I post the parent (Question) :
Question form
$builder
->add('possibleAnswers', CollectionType::class, array(
'entry_type' => PossibleAnswerType::class,
'allow_add' => true,
))
;
PossibleAnswer form :
$builder
->add('title')
;
And the json looks like :
{
"title": "my question",
"possibleAnswers": [
{
"title": "my first answer"
}
]
}
Hope it can help.
Edit :
If you want to link a PossibleAnswer to a Question while creating you Question you can use this :
Question form :
$builder
->add('possibleAnswer', EntityType::class, array(
'class' => YOUR_ENTITY::class,
'multiple' => true
));
And you json should only contains the id of the entity you want to link to. It should be like this :
{
"title": "a postman created question",
"answerConditions": [
1
]
}

Logstash filter parse json file result a double fields

I am using the latest ELK (Elasticsearch 1.5.2 , Logstash 1.5.0, Kibana 4.0.2)
I have a question that
sample .json
{ "field1": "This is value1", "field2": "This is value2" }
longstash.conf
input {
stdin{ }
}
filter {
json {
source => "message"
add_field =>
{
"field1" => "%{field1}"
"field2" => "%{field2}"
}
}
}
output {
stdout { codec => rubydebug }
elasticsearch {
host => "localhost"
index => "scan"
}
}
Output:
{
"message" => "{ \"field1\": \"This is value1\", \"field2\": \"This is value2\" }",
"#version" => "1",
"#timestamp" => "2015-05-07T06:02:56.088Z",
"host" => "myhost",
"field1" => [
[0] "This is value1",
[1] "This is value1"
],
"field2" => [
[0] "This is value2",
[1] "This is value2"
]
}
My question is 1) why the field result appear double in the result? 2) If there is nested array , how is it should reference in the logstash configure?
Thanks a lot!
..Petera
I think you have misunderstood what the json filter does. When you process a field through the json filter it will look for field names and corresponding values.
In your example, you have done that with this part:
filter {
json {
source => "message"
Then you have added a field called "field1" with the content of field "field1", since the field already exists you have just added the same information to the field that was already there, it has now become an array:
add_field =>
{
"field1" => "%{field1}"
"field2" => "%{field2}"
}
}
}
If you simplify your code to the following you should be fine:
filter {
json {
source => "message"
}
}
I suspect your question about arrays becomes moot at this point, as you probably don't need the nested array, and therefore, won't need to address it, but in case you do, I believe you can do this like so:
[field1][0]
[field1][1]

Laravel 4 Response

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)