-1

I'm trying to read multiple data from this JSON file but I keep getting various errors like; "Uncaught Error: Cannot use object of type stdClass as array in" or "Trying to get property 'title' of non-object in". Where am I doing wrong?

$jsonObject = '{
  "@context": "http://schema.org",
  "@type": "JobPosting",
  "title": "UX Designer",
  "url": "https://www.google.com",
  "datePosted": "2019-03-15T16:38+00:00",
  "validThrough": "2019-03-22T16:38+00:00",
  "description": "Description",
  "industry": "IT",
  "employmentType": "Permanent",
  "hiringOrganization": {
    "@type": "Organization",
    "name": "PCR",
    "url": "https://www.google.com",
    "logo": "https://www.google.com"
  },
  "jobLocation": {
    "@type": "Place",
    "address": {
      "@type": "PostalAddress",
      "addressLocality": "Acton Green",
      "addressRegion": "London",
      "postalCode": "W4 5YB",
      "addressCountry": "GB"
    },
    "geo": {
      "@type": "GeoCoordinates",
      "latitude": "51.4937",
      "longitude": "-0.275693"
    }
  }
}';

$baz = json_decode($jsonObject);
echo($baz[0]->addressRegion); 
m12l
  • 65
  • 9

2 Answers2

0
$baz = json_decode($jsonObject);
echo $baz->jobLocation->address->addressRegion; 
0

You try to get index 0 of the array. However, variable is not the array, it is object. When you decode it, you have to reach elements with their headers.

For example if you want to get datePosted, the structure is

echo $baz->datePosted

and if you want to get addressRegion it is simply

echo $baz->jobLocation->address->addressRegion

the result of the print_r($baz);

stdClass Object
(
    [@context] => http://schema.org
    [@type] => JobPosting
    [title] => UX Designer
    [url] => https://www.google.com
    [datePosted] => 2019-03-15T16:38+00:00
    [validThrough] => 2019-03-22T16:38+00:00
    [description] => Description
    [industry] => IT
    [employmentType] => Permanent
    [hiringOrganization] => stdClass Object
        (
            [@type] => Organization
            [name] => PCR
            [url] => https://www.google.com
            [logo] => https://www.google.com
        )

    [jobLocation] => stdClass Object
        (
            [@type] => Place
            [address] => stdClass Object
                (
                    [@type] => PostalAddress
                    [addressLocality] => Acton Green
                    [addressRegion] => London
                    [postalCode] => W4 5YB
                    [addressCountry] => GB
                )

            [geo] => stdClass Object
                (
                    [@type] => GeoCoordinates
                    [latitude] => 51.4937
                    [longitude] => -0.275693
                )

        )

)