How to convert JSON string to array

XMen picture XMen · Sep 22, 2011 · Viewed 476.6k times · Source

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.

Answer

RickN picture RickN · Sep 22, 2011

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.