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

172

我想要做的是:

  1. 从 PHP 文本区域获取 JSON 输入
  2. 使用此输入并将其转换为 JSON,然后将其传递给 PHP curl 发送请求。

我从 API 的 GET 请求中得到了这个 JSON 字符串,我想将其传递给 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);

上述代码没有返回数组。


1
你需要将JSON字符串转换为数组,还是想从该数据中伪造一个URL?具体问题是什么? - Janis Veinbergs
那它没有给出什么?你从文本区域中获取一个JSON格式的字符串,然后将其转换为JSON? - PeeHaa
1
如果你在我的问题中使用json_decode(,true)来处理以上的JSON,它会返回一个数组。 - XMen
@Pekka 请再次检查我的问题。 - XMen
3
无效的JSON问题。 - XMen
显示剩余3条评论
17个回答

246
如果将您POST的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.

如果您在我的问题中使用json_decode(, true)来处理上述JSON,它会返回一个数组吗? - XMen
如果您使用的是PHP内置的json_decode(),则如果您的JSON无效(例如,没有引用键),它将返回NULL。这就是文档中所说的,也是我的PHP 5.2安装返回的结果。您是否使用了除官方内置的json_decode()之外的其他函数?var_dump(json_decode($str, true));返回什么? - RickN
在进行json编码后,我想将每个单独的json对象(例如{foo:“bar”})作为数组中的对象读取。我该如何从json编码数据创建一个数组以读取每个json对象?@RikkusRukkus - Manny265
@Manny265,那听起来像是值得开一个新问题来讨论的。请在问题中提供以下内容:(1)一些示例代码,(2)你已经尝试过的方法,以及(3)期望的结果。而不是在评论区回复。 - RickN

153

试试这个:

$data = json_decode($your_json_string, TRUE);
第二个参数将把解码后的JSON字符串转换为关联数组。

38
如果您使用$_REQUEST$_GET$_POST从表单获取JSON字符串,则需要使用html_entity_decode()函数。我在将请求内容与复制到的内容进行var_dumpecho对比后才意识到这一点,并且注意到请求字符串要大得多。

正确方式:

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

2
太好了,这个可行。当我从$_POST函数获取数据时,json_last_error()的值为JSON_ERROR_SYNTAX。但一切都很好。这是解码错误而不是编码错误,比如ASCII或UTF8。谢谢。 - user1817927

13
使用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)
}

8

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

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

输出:

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

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

        )

)

它在结尾处有一个真值 - Prince Hamza

8
如果你正在使用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));

4

如果你想转换成一个对象,则:

$data = json_decode($yourJson);

如果你想转换成数组,则:

$data = json_decode($yourJson,TRUE);

3
这是我的解决方案: 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 }

3
你可以将JSON对象转换为数组和字符串。
$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++;
}

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

?>

我认为这应该可以工作,只是如果键不是数字,那么键也应该用双引号括起来。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接