简体   繁体   中英

Can't seem to get data from json

I have a simple web app were I'm getting json from the front-end of the app. I have an object which contains few properties and an array of objects.

It looks like this:

{
"first_name": "test",
"last_name": "test2",
"id": "1234",
"cars": [{
        "model": "car_model",
        "make": "car_maker",
        "year": "1234",
        "owned_since": "3456"
    },
    {
        "model": "car_model",
        "make": "car_maker",
        "year": "1234",
        "owned_since": "3456"
    }
  ]
}

I get this JSON by using JSON.stringify the object on the frontend. I send it with axios has a POST request to my PHP Laravel backend and I want to parse it.

This is what I have:

public function store() { 
    $json = json_decode(request()->getContent(), true);
}

I tried to get my json data like this:

public function store() { 
    $json = json_decoder(request()->getContent, true);
    $first_name = $json -> first_name;
    for($json->cars as $key => $value) {
        
    }
}

But it just won't work. I always get an error that I try to access first_name on the object and it does not exist. I also tried this way:

public function store() { 
$json = json_decoder(request()->getContent);
$first_name = $json['first_name'];
for($json['cars'] as $key => $value) {
    
}
}

But I also got the same problem. What am I doing wrong, I saw few different answers about this topic, but just couldn't get it to work.

If you are attempting to POST the data but can't seem to access the data in back-end, I would suggest you to check for any raw POST data.

You can check for any raw POST data like this:

$postData = file_get_contents('php://input');
print_r($postData);

The reason for this is because PHP doesn't support JSON data when populating $_POST.

It only supports:

  • application/x-www-form-urlencoded
  • multipart/form-data

(complete answer here: https://stackoverflow.com/a/42507767/2906013 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM