How to convert JSON string to array

What I want to do is the following:

  1. taking JSON as input from text area in php
  2. use this input and convert it to JSON and pass it to php curl to send request.

this m getting at php from get of api this json string i want to pass to json but it is not converting to array

echo $str='{
        action : "create",
        record: {
            type: "n$product",
            fields: {
                n$name: "Bread",
                n$price: 2.11
            },
            namespaces: { "my.demo": "n" }
        }
    }';
    $json = json_decode($str, true);

the above code is not returning me array.


Solution 1:

If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys:

json_decode('{foo:"bar"}');         // this fails
json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar")
json_decode('{"foo":"bar"}');       // returns an object, not an array.

Solution 2:

Try this:

$data = json_decode($your_json_string, TRUE);

the second parameter will make decoded json string into an associative arrays.

Solution 3:

If you are getting the JSON string from the form using $_REQUEST, $_GET, or $_POST the you will need to use the function html_entity_decode(). I didn't realize this until I did a var_dump of what was in the request vs. what I copied into and echo statement and noticed the request string was much larger.

Correct Way:

$jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);

With Errors:

$jsonText = $_REQUEST['myJSON'];
$myArray = json_decode($jsonText, true);
echo json_last_error(); //Returns 4 - Syntax error;