php - json_decode() returns null instead an array
Get the solution ↓↓↓I am going to INSERT an array of objects into mysql via AJAX but on server sidejson_decode()
returnsnull
How can i solve this?
This is the ajax codes:
let mainObj = [
{ username: 'david', password: 33456, email: '[email protected]' },
{ username: 'rose', password: 3333, email: '[email protected]' },
{ username: 'adam', password: 95112, email: '[email protected]' },
{ username: 'lisa', password: 'sarlak', email: '[email protected]' },
]
let sendMe = JSON.stringify(mainObj);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
}
xhr.open("GET", "check.php?x=" + sendMe, true);
xhr.send();
And the php codes (check.php):
$obj= json_decode($_GET['x'], true);
$b= $obj[1]->username;
var_dump($b);
It returnsnull
but i need it returns an array of objects which be usable in database.
Answer
Solution:
Something like this (others already wrote it..):
$json = '[{"username":"david","password":33456,"email":"[email protected]"},{"username":"rose","password":3333,"email":"[email protected]"},{"username":"adam","password":95112,"email":"[email protected]"},{"username":"lisa","password":"sarlak","email":"[email protected]"}]';
$decodedJson = json_decode($json, true);
// $b= $decodedJson[1]->username; // Wrong, you have an array, not object
// Correct
foreach($decodedJson as $single) {
print_r($single["username"]."\n");
}
// Prints out:
david rose adam lisa
Answer
Solution:
Since you're using the second parametertrue
in$obj= json_decode($_GET['x'], true);
your returned$obj
will be an array. You either use:
$obj = json_decode($_GET['x']);
$b = $obj[1]->username;
or
$obj = json_decode($_GET['x'], true);
$b = $obj[1]['username'];
to get "rose".
Answer
Solution:
You are trying to treat an array as an object,json_decode
returns an array not an object or stdclass... instead of
$b= $obj[1]->username;
should be
$b= $obj[1]['username'];
I'm assuming that you are not using any framework since the thing that you did should throw and exception so it's better to enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your lock file does not contain a compatible set of packages. please run composer update
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.