Reputation: 1655
I have the following code:
$option = $this->request->post['option'];
var_dump($option);
echo "<br>";
var_dump(json_decode($option));
The dumps show:
string(118) "{'product_option_id':276, 'product_option_value_id':132, 'name':'Цветове', 'value':'Бял', 'type':'select'}"
And the second one (json_decode):
NULL
Why the string can't be parsed ?
EDIT: now my json looks like this:
string(205) "{"product_option_id": 280, "product_option_value_id": 133, "name": "Цветове", "value": "Бежов", "type": "select"}"
And i added this to my code:
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
and i returns Syntax error, malformed JSON
Upvotes: 0
Views: 1231
Reputation: 527
refer Convert a string to JSON object php
you can use
$result = (array) json_decode($option);
or
$result = json_decode($option, true);
Upvotes: 0
Reputation: 12513
Single quotes are not allowed in JSON, only double quotes. Do
$option = str_replace ("'", '"', $option);
before calling json_decode
.
Upvotes: 1
Reputation: 1450
See this SO answer: https://stackoverflow.com/a/4162651/174326
If you wrap your strings in your JSON string with double quotes it'll work:
json_decode('{"product_option_id":276, "product_option_value_id":132, "name":"Цветове", "value":"Бял", "type":"select"}')
Upvotes: 1