user1400382
user1400382

Reputation: 9

Trying to Get Property of non-object in PHP JSON

I am getting the following variable, which I put in a variable $request:

{
"id":0,
"person_name":"Altensis DominicX",
"age":"14",
"dob":"22/02/2004",
"sex":"male",
"marital_status":"singleX",
"addr_name":"Fetles Ingus IncX",
"po_box":"box 41",
"post_office":"SYDKK",
"district":"XXCity",
"phones":"456-234",
"fax":"8525",
"email":"[email protected]",
"person_type":"1",
"phy_addr":"XXL Business CentreX",
"religion":"none",
"case_no":"case 1",
"username":"user nameX",
"pwd":"password",
"req_code" = "1"
}

When I do

$values = json_encode($request);

I get:

"{\r\n\"id\":0,\r\n\"person_name\":\"Altensis DominicX\",\r\n\"age\":\"14\",\r\n\"dob\":\"22\/02\/2004\",\r\n\"sex\":\"mal\",\r\n\"marital_status\":\"singleX\",\r\n\"addr_name\":\"Fetles Ingus IncX\",\r\n\"po_box\":\"box 41\",\r\n\"post_office\":\"LL 1\",\r\n\"district\":\"LilongweX\",\r\n\"phones\":\"456-234\",\r\n\"fax\":\"8525\",\r\n\"email\":\"[email protected]\",\r\n\"person_type\":\"1\",\r\n\"phy_addr\":\"Balaka Business CentreX\",\r\n\"religion\":\"IslamX\",\r\n\"case_no\":\"case 1\",\r\n\"username\":\"user nameX\",\r\n\"pwd\":\"password\",\r\n\"req_code\" = \"1\"\r\n}"

I want to get the values of id, person_name etc. But when I do

$var_id = $values->id; 

I get

h1>500 Internal Server Error

Trying to get property of non-object (8)

#0 /var/www/html/myapp/index.php(175): flight\Engine->handleError(8, 'Trying to get p...', '/var/www/html/m...', 175, Array)

I have tried

$values = json_decode($request);

but nothing seems to work.

What I am not doing right?

Upvotes: 0

Views: 1708

Answers (2)

hassan
hassan

Reputation: 8288

you are encoding the 'encoded' json

$values = json_encode($request);

you need to reverse this , by decoding the $request variable instead of re-encoding it by :

$values = json_decode($request);

by the way you have typo in your json , it is invalid json

replacing this "req_code" = "1" by "req_code": "1" will solve your issue

https://3v4l.org/RumGf

Upvotes: 2

Jakob Vibe
Jakob Vibe

Reputation: 11

First of all your json is not valid... Using a json linter will show:

Error: Parse error on line 21: ...sword", "req_code" = "1"} ----------------------^ Expecting 'EOF', '}', ':', ',', ']', got 'undefined'

After you correct the "=" to a ":" use json_decode and then your code will fly :)

Upvotes: 1

Related Questions