如何将JSON字符串转换为数组

时间:2011-09-22 08:27:48

标签: php arrays json

我想做的是以下内容:

  1. 从php
  2. 中的文本区域输入JSON作为输入
  3. 使用此输入并将其转换为JSON并将其传递给php curl以发送请求。
  4. 这是从获取api这个json字符串获取php我希望传递给json但是它没有转换为数组

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

    上面的代码没有返回我的数组。

15 个答案:

答案 0 :(得分:153)

如果您将帖子中的JSON传递给json_decode,则会失败。有效的JSON字符串有引用键:

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.

答案 1 :(得分:80)

试试这个:

$data = json_decode($your_json_string, TRUE);

第二个参数将解码的json字符串转换为关联数组。

答案 2 :(得分:22)

如果您使用$_REQUEST$_GET$_POST从表单中获取JSON字符串,则需要使用函数html_entity_decode()。我没有意识到这一点,直到我做了var_dump请求中的内容与我复制到echo语句中的内容,并注意到请求字符串要大得多。

正确方式:

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

有错误:

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

答案 3 :(得分:10)

使用json_decode($json_string, TRUE)函数将JSON对象转换为数组。

示例:

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

$my_array_data = json_decode($json_string, TRUE);

注意:第二个参数会将已解码的JSON字符串转换为关联数组。

===========

<强>输出:

var_dump($my_array_data);

array(5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

答案 4 :(得分:5)

如果您使用file_get_contents从URL获取json字符串,请按照以下步骤操作:

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

答案 5 :(得分:4)

您的字符串应采用以下格式:

maxn = 0
for i in range(1, d + 1):

    if (n%i == 0 and m%i == 0):
        maxn = i

return maxn

输出:

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

答案 6 :(得分:1)

如果您需要将JSON文件或结构转换为具有所有嵌套级别的PHP样式数组,则可以使用此功能。首先,你必须json_decode($ yourJSONdata),然后将它传递给这个函数。它将向您的浏览器窗口(或控制台)输出正确的PHP样式数组。

https://github.com/mobsted/jsontophparray

答案 7 :(得分:1)

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

?>

我认为这应该有效,只是如果它们不是数字,那么Keys也应该是双引号。

答案 8 :(得分:1)

确保字符串采用以下JSON格式,如下所示:

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

如果没有,那么您可以在请求参数中添加"responsetype => json"

然后使用json_decode($response,true)将其转换为数组。

答案 9 :(得分:1)

您可以将json对象转换为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++;
}

答案 10 :(得分:1)

<块引用>

您调用 json 的字符串有问题。我在下面对其进行了一些更改。如果您将字符串正确格式化为正确的 json,则下面的代码将起作用。

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

答案 11 :(得分:0)

使用此转换器,它根本不会失败: 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);

答案 12 :(得分:0)

这是我的解决方案: json字符串$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}]"

所以我使用json_decode两次:

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

var_dump($js_column_validation);

结果是:

 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 }

答案 13 :(得分:0)

您可以按如下方式将字符串更改为JSON,如果需要,还可以修剪,删除字符串

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

答案 14 :(得分:-2)

$data = json_encode($result, true);

echo $data;