How to load json file into Laravel Controller? - json

I have a JSON file that I would like to load into a controller in Laravel so that I can use the data into my application.
The files path is /storage/app/calendar_Ids.json.
What is the correct way to go about doing this?

Here, this should help you get sorted.
use Storage;
$json = Storage::disk('local')->get('calendar_Ids.json');
$json = json_decode($json, true);

Try this
$path = '/storage/app/calendar_Ids.json';
$content = json_decode(file_get_contents($path), true);`
Then just dd($content); to see if it works.

You can try this too:
$json = file_get_contents('your json file path here.....');
//converting json object to php associative array
$data = json_decode($json, true);
foreach($data as $item){
DB::table('table name')->insert(
array(
'clientId' => $item['clientId'],
'socialMediaLinkId' => $item['socialMediaLinkId'],
'link' => $item['link'],
'isEnabled' => $item['isEnabled'],
'created_at' => $item['created_at'],
'updated_at' => $item['updated_at'],
'isSelectedByDefault' =>$item['isSelectedByDefault'],
'showOnNegativePage' =>$item['showOnNegativePage']
)
);
}

You can try this too:
$json = storage_path('folder/filename.json');

Related

cURL retrieve json data and store in mysql database from url

i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>

Unable to open file for reading [filename.pdf] yii2 swiftmailer

I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.

How to parse JSON/REST data from server using Perl

Im trying to parse out JSON output from the server using Perl. The connection and downloading of the REST data is ok, I just need help parsing the returned data. Here is the snippet for my code:
my $response = HTTP::Tiny->new->get($SERVER_ADDR);
if ($response->{success})
{
my $html = $response->{content};
#LINES = split /\n/, $html;
chomp(#LINES);
print("Lines: '#LINES'\n"); # ZZZ
my $decoded_json = decode_json( $html );
print Dumper $decoded_json;
}
else
{
print "Failed: $response->{status} $response->{reasons}";
}
And here is the results:
Lines: '{"players":[{"currentlyOnline":false,"timePlayed":160317,"name":"MarisaG","lastPlayed":1474208741470}]}'
$VAR1 = {
'players' => [
{
'currentlyOnline' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'timePlayed' => 160317,
'lastPlayed' => '1474208741470',
'name' => 'MarisaG'
}
]
};
There will be multiple entries under the "players" for each player logged in right now. Any tips?
I'm not really sure what you're asking. You have successfully parsed the JSON by by calling decode_json(). You now have a data structure in $decoded_json. Your call to Dumper() shows the structure of that data. It's a hash reference with a single key, players. The value associated with that key is an array reference. Each element in the referenced array is another hash.
So, for example, you could print all of the players' names with code like this.
foreach (#{ $decoded_json->{players} }) {
say $_->{name};
}

json cannot be decode

I have a problem with json,
I'm using PHP Curl to post file with form-data, and after post the Curl return some weird json
like this
{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}
the problem is, the return result can't be json_decode, I know if this json weird, I can print but cannot be json_decode,
I not have acces to change API, I need the id from badges,
is there any trick? or a way to get the id, or some modified so the return result can be decode
i have tried
$a = 'that result';
$b = "'".$a."'";
$c = json_decode($b);
but it still json format, not become array
need some idea and help, thx
EDITED:
let's say
$result = {"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}
when I json_decode
$data = json_decode($result);
var_dump($result );
print_r($data);
it will return
{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}bool(true) 1
try this
$js='{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}';
var_dump(json_decode($js,true));
Your Output will be
array (size=3)
'code' => int 200
'status' => string 'Success' (length=7)
'badges' =>
array (size=6)
'id' => string '0d28f02d13fe4c7ca8681e2ed0224180' (length=32)
'name' => string 'test 5' (length=6)
'description' => string 'test 5' (length=6)
'image' => string 'http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg' (length=66)
'category' => string 'Upload' (length=6)
'target' => int 2
You don't want to put quotes around the string. Change
$a = 'that result';
$b = "'".$a."'";
$c = json_decode($b);
to simply
$a = 'that result';
$c = json_decode($a);
The JSON is valid. Putting the quotes around it made it invalid.
The original response is correct JSON syntax. Don't add the extra quotes in $b = "'".$a."'"; //INCORRECT
Instead try this, as an example:
/* $response is the result from API */
$response = '{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180"}}';
$decoded = json_decode($response);
print_r($decoded); //See full decoded
$badge_id = $decoded->badges->id;
echo "The badge id is $badge_id \n";
Which would print:
stdClass Object
(
[code] => 200
[status] => Success
[badges] => stdClass Object
(
[id] => 0d28f02d13fe4c7ca8681e2ed0224180
)
)
The badge id is 0d28f02d13fe4c7ca8681e2ed0224180

manipulating a JSON to correct format in perl

I have a JSON that prints
{"d":{"success":true,"drivers":[{"FIRST_NAME":"JOHN","LAST_NAME":"SMITH"},{"FIRST_NAME":"JANE","LAST_NAME":"DOE"}]}}
The names change depending on what was found in the database. I need to push this in this format for each result resturned in the JSON:
push(#$dummy_data, {'name' => 'testname', 'key' => 'somekey-1234'});
push(#$dummy_data, {'name' => 'testname2', 'key' => 'somekey-5678'});
So for this example it would be John Smith in place of testname and Jane for testname2
How would I do this so for each first and last name in the json gets pushed in the format above?
Let's try this new game
use strict; use warnings;
use JSON::XS;
use Data::Dumper;
# creating reference to a void ARRAY
my $dummy_data = [];
# creating $json string
my $json = '{"d":{"success":true,"drivers":[{"FIRST_NAME":"JOHN","LAST_NAME":"SMITH"},{"FIRST_NAME":"JANE","LAST_NAME":"DOE"}]}}';
# converting JSON -> Perl data structure
my $perl_hash = decode_json $json;
# feeding $dummy_data ARRAY ref with a HASH
push #$dummy_data, {
name => $perl_hash->{d}->{drivers}->[0]->{FIRST_NAME},
key => $perl_hash->{d}->{drivers}->[1]->{FIRST_NAME}
};
# print what we have finally
print Dumper $dummy_data;
Output
$VAR1 = [
{
'name' => 'JOHN',
'key' => 'JANE'
}
];