简体   繁体   中英

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.

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.

Try this:

$data = json_decode($your_json_string, TRUE);

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

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;

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

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));

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
                )

        )

)

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++;
}

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

<?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.

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 }

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.

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>';

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);

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;
 <?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);
 

if you want to convert to object then $data = json_decode($yourJson);

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'])

$data = json_encode($result, true);

echo $data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM