169

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.

XMen
  • 29,384
  • 41
  • 99
  • 151

17 Answers17

245

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.
RickN
  • 12,537
  • 4
  • 24
  • 28
  • if you do the above json in my question json_decode(, true) does it retuns an array – XMen Sep 22 '11 at 09:09
  • @RahulMehta If you're using PHP's built-in `json_decode()` it will return `NULL` if your JSON is invalid (for example, no quoted keys). That's what the documentation says and that's what my PHP 5.2 installation returns. Are you using a function other than the official, built-in `json_decode()`? What does `var_dump(json_decode($str, true));` return? – RickN Sep 22 '11 at 15:34
  • after json_encoding, I'd like to read each individual json object e.g. {foo:"bar"} as an object in the array. how can I create an array from the json_encoded data to read each json object? @RikkusRukkus – Manny265 Oct 03 '18 at 08:48
  • @Manny265 that sounds like something that deserves its own question with (1) some sample code, (2) what you have tried so far and (3) the expected outcome, rather than this comment section. – RickN Oct 03 '18 at 10:04
151

Try this:

$data = json_decode($your_json_string, TRUE);

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

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
sepidol
  • 1,681
  • 1
  • 9
  • 5
37

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;
aksu
  • 5,221
  • 5
  • 24
  • 39
jbeauchamp
  • 379
  • 3
  • 2
  • 2
    Perfect, this works. when I get data from $_POST function json_last_error() was = to JSON_ERROR_SYNTAX. but all allways was fine. It was error of decode not error of encode like ascii or utf8. THANKS –  Feb 09 '16 at 18:36
13

Use json_decode($json_string, TRUE) function to convert the JSON object to an array.

Example:

$json_string   = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$my_array_data = json_decode($json_string, TRUE);

NOTE: The second parameter will convert decoded JSON string into an associative array.

===========

Output:

var_dump($my_array_data);

array(5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
Trimax
  • 2,413
  • 7
  • 35
  • 59
Arslan Ramay
  • 1,042
  • 9
  • 15
8

If you are getting json string from URL using file_get_contents, then follow the steps:

$url = "http://localhost/rest/users";  //The url from where you are getting the contents
$response = (file_get_contents($url)); //Converting in json string
 $n = strpos($response, "[");
$response = substr_replace($response,"",0,$n+1);
$response = substr_replace($response, "" , -1,1);
print_r(json_decode($response,true));
Himanshu
  • 31,810
  • 31
  • 111
  • 133
piyush
  • 81
  • 1
  • 1
8

your string should be in the following format:

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

echo "<pre>";
print_r($array);

Output:

Array
 (
    [action] => create
    [record] => Array
        (
            [type] => n$product
            [fields] => Array
                (
                    [n$name] => Bread
                    [n$price] => 2.11
                )

            [namespaces] => Array
                (
                    [my.demo] => n
                )

        )

)
Dinanath Thakur
  • 686
  • 4
  • 9
3

this my solution: json string $columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]"

so i use json_decode twice like that :

$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation); 

var_dump($js_column_validation);

and the result is :

 array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL }
Mourad MAMASSI
  • 849
  • 1
  • 11
  • 14
3

You can convert json Object into Array & String.

$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';

$b=json_decode($data);

$i=0;
while($b->{'resultList'}[$i])
{
    print_r($b->{'resultList'}[$i]->{'displayName'});
    echo "<br />";
    $i++;
}
Manav Akela
  • 166
  • 2
3

If you want to convert to an object then:

$data = json_decode($yourJson);

if you want to convert to an array then:

$data = json_decode($yourJson,TRUE);
Saman Salehi
  • 1,004
  • 1
  • 12
  • 19
Bhimani Rutvik
  • 398
  • 2
  • 13
2
<?php
$str='{
    "action" : "create",
    "record" : {
                "type": "$product",
                "fields": {
                           "name": "Bread",
                           "price": "2.11"
                           },
                "namespaces": { "my.demo": "n" }
                }
    }';
echo $str;
echo "<br>";
$jsonstr = json_decode($str, true);
print_r($jsonstr);

?>

i think this should Work, its just that the Keys should also be in double quotes if they are not numerals.

Pradeep Dhawan
  • 126
  • 1
  • 7
2

Make sure that the string is in the following JSON format which is something like this:

{"result":"success","testid":"1"} (with " ") .

If not, then you can add "responsetype => json" in your request params.

Then use json_decode($response,true) to convert it into an array.

Nick
  • 1,032
  • 16
  • 27
  • 1
    Welcome to StackOverflow :-) The community is always happy for new members who want to contribute to it and appreciates your attitude. Sadly another member thought your answer deserves a downvote. This might be, because the question itself was asked about seven years ago and was already answered several times. In addition the `responseType` property is used to determine the type of the data in the answer to the request. Yet the problem is, that the request body contains data that is not in the correct fromat itself. Your answer therefore does not fit the given context. – Philipp Maurer Jan 16 '18 at 14:36
2

There is a problem with the string you are calling a json. I have made some changes to it below. If you properly format the string to a correct json, the code below works.

$str = '{
        "action" : "create",
        "record": {
            "type": "n$product",
            "fields": {
                "nname": "Bread",
                "nprice": 2.11
            },
            "namespaces": { "my.demo": "n" }
        }
    }';

    $response = json_decode($str, TRUE);
    echo '<br> action' . $response["action"] . '<br><br>';
Junior
  • 1,007
  • 4
  • 16
  • 26
2
 <?php

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

 $json = json_decode($str,true);
 echo '<pre>';
 print_r($json);
 

this should Work,just that the Keys should also be in double quotes if they are not numerals.

output:-

  Array
 (
   [action] => create
   [record] => Array
     (
        [type] => n$product
        [fields] => Array
            (
                [n$name] => Bread
                [n$price] => 2.11
            )

         [namespaces] => Array
             (
                 [my.demo] => n
             )
       )
     ) 

It will convert Json String To Array

Suhasini
  • 91
  • 1
  • 4
  • Hi and thanks for the answer. It would be great if you could explain what your code does. It would help the community much more that way to learn from you! – Simas Joneliunas Feb 03 '22 at 04:46
1

If you ever need to convert JSON file or structures to PHP-style arrays, with all the nesting levels, you can use this function. First, you must json_decode($yourJSONdata) and then pass it to this function. It will output to your browser window (or console) the correct PHP styled arrays.

https://github.com/mobsted/jsontophparray

1

Use this convertor , It doesn't fail at all: Services_Json

// create a new instance of Services_JSON
$json = new Services_JSON();

// convert a complexe value to JSON notation, and send it to the browser
$value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
$output = $json->encode($value);
print($output);
// prints: ["foo","bar",[1,2,"baz"],[3,[4]]]

// accept incoming POST data, assumed to be in JSON notation
$input = file_get_contents('php://input', 1000000);
$value = $json->decode($input);

// if you want to convert json to php arrays:
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
Farhad Sakhaei
  • 894
  • 10
  • 28
1

You can change a string to JSON as follows and you can also trim, strip on string if wanted,

$str = '[{"id":1, "value":"Comfort Stretch"}]';

//here is JSON object
$filters = json_decode($str);

foreach($filters as $obj){
   $filter_id[] = $obj->id;
}

//here is your array from that JSON
$filter_id;
Shahrukh Anwar
  • 2,544
  • 1
  • 24
  • 24
0

You can use this to get an object of your JSON data by setting it as object before you decode the data. This only works if you send the object as a JSON string

$data = (object)json_decode($_POST['data'])