Home > Software design >  AWS S3 - accessing and working with JSON files
AWS S3 - accessing and working with JSON files

Time:05-13

I am trying to read a json file from AWS S3.

I can access the file and print out the json value but it won't let me do anything with it.

It is giving me an error saying: 'Recoverable fatal error: Object of class stdClass could not be converted to string' even though it is type set as a string.

What I have is as follows:

<?php
require "../vendor/autoload.php";
use Aws\S3\S3Client;

$aws_credentials = [
    'region' => 'eu-west-1',
    'version' => 'latest',
    'credentials' => [
        'key' => 'xxxxxxxxx',
        'secret' => 'xxxxxxxxxxxxxxxx'
    ]
];

$aws_client = new S3Client($aws_credentials);

$bucket = 'xxxxxxx';
$file_name = 'data.json';

$result = $aws_client->getObject(array(
    'Bucket' => $bucket,
    'Key'    => $file_name
));

$json = (string)$result['Body'];

echo $json; // this outputs the json I want to work with
echo '<br />';
echo gettype($json); // this outputs 'string'
echo '<br />';
echo json_decode($json); // this outputs 'Recoverable fatal error:  Object of class stdClass could not be converted to string'

?>

CodePudding user response:

The input to json_decode is a string, but the output of that function is an object.

You then pass that output to echo, but echo needs to convert it to a string, and doesn't know how.

This is probably clearer if we assign the output to a variable:

echo gettype($json); // this outputs 'string'
echo '<br />';
$object = json_decode($json);
echo gettype($object); // this will output 'object'
var_dump($object); // this will show you what's in the object
echo $object; //  this is an error, because you can't echo an object
  • Related