3

I am getting the error undefined property data while trying to access the data array returned from a json response.

{
    "data": [
        {---},
        {---}
    ],
    "links": {---},
    "meta": {---}
}

i am accessing the data like this,

$posts->data

just for the record i have tried $posts->data[0] and "$posts["data"] but none works.

jelhan
  • 6,149
  • 1
  • 19
  • 35
jadii_
  • 39
  • 3

2 Answers2

4

This is a json you can not access it using object/array methods.

1st you must decode your json object like:

 $posts = json_decode($posts);  //object output

 $posts = json_decode($posts,true); //array output

And then access it like:

 $posts->data     //object

 $posts['data']  //array

Keep an eye on the nested data array. In order to access the values inside it you will have to loop around it.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
  • sorry i forgot to mention it before but i did try `json_decode()` but it gives the **error:json_decode() expects parameter 1 to be string** – jadii_ Dec 12 '19 at 08:41
  • Then your output is not what you are showing us. If your `$posts` was the json you put in your question description json_decode would have worked. – pr1nc3 Dec 12 '19 at 08:42
  • it's exactly the same i have just removed the data inside each property just to make it more compact and easy to understand. – jadii_ Dec 12 '19 at 08:49
  • What you are saying is not possible, check your code. A json is a string and json_decode expects a string input. By getting the error you mentioned means that $posts is not a json string. Try to var_dump it but for sure your variable $posts does not hold a json string type value. Maybe you overwrite it ? Maybe it's null at the point you try to decode? Maybe it's an array or something but for sure it's not a json string – pr1nc3 Dec 12 '19 at 08:52
  • yeah i understand that, the response am getting was actually a json object, **ErrorException: json_decode() expects parameter 1 to be string, object given** – jadii_ Dec 12 '19 at 08:59
  • Then do something like: `json_decode(json_encode($posts));` Again try to debug it and var_dump $posts before you decode it to see the type of your variable and what it actually looks like, cause it is not a json. – pr1nc3 Dec 12 '19 at 09:31
  • so now with `json_decode(json_encode($posts));` i am getting what's in the **data** but the other two properties **meta** and **links** are not there,i mean they just got disappeared. I am halfway to what i want from json which is `data` and the other half is the `links` ,but anyways thanks alot really appreciate your help. – jadii_ Dec 12 '19 at 13:29
0

Are you sure you get array in that response? Try to dump whole response and check what do you get.