0

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

2
  • 1
    Possible duplicate of Single vs double quotes in JSON Commented Sep 19, 2017 at 9:29
  • Question: What character encoding scheme are you using? If anything other than UTF-8 that may be your problem. Commented Sep 19, 2017 at 10:13

3 Answers 3

1

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"}')

Sign up to request clarification or add additional context in comments.

1 Comment

I've done it the result is still the same my first dump now looks like this: string(196) "{"product_option_id":276, "product_option_value_id":132, "name":"Цветове", "value":"Бял", "type":"select"}"
1

Single quotes are not allowed in JSON, only double quotes. Do

$option = str_replace ("'", '"', $option);

before calling json_decode.

1 Comment

now its looks like this: string(196) "{"product_option_id":276, "product_option_value_id":132, "name":"Цветове", "value":"Бял", "type":"select"}" , but the result is still null
0

refer Convert a string to JSON object php

you can use

$result = (array) json_decode($option);

or

$result = json_decode($option, true);

1 Comment

when you convert null to array you receive array(0) {}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.