【问题标题】:How to convert JSON string to array如何将 JSON 字符串转换为数组
【发布时间】:2011-11-22 15:11:35
【问题描述】:

我想做的是:

  1. 将 JSON 作为 php 文本区域的输入
  2. 使用此输入并将其转换为 JSON 并将其传递给 php curl 以发送请求。

这个 m 从 api 获取到 php 这个 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);

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

【问题讨论】:

  • 您需要将 json 字符串转换为数组还是要从该数据中伪造一个 url?究竟是什么问题?
  • then it is not giving 不给什么?您从 textarea 中获取 JSON 格式的字符串并将其转换为 JSON???
  • 如果您在我的问题 json_decode(, true) 中执行上述 json,它会重新调整数组
  • @Pekka 请再次检查我的问题。
  • 这是无效的 json 问题。

标签: php arrays json


【解决方案1】:

试试这个:

$data = json_decode($your_json_string, TRUE);

第二个参数将解码后的json字符串变成一个关联数组。

【讨论】:

  • 非常感谢! =)
【解决方案2】:

如果您将帖子中的 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,它会重新调整数组
  • @RahulMehta 如果您使用 PHP 的内置 json_decode(),如果您的 JSON 无效(例如,没有引用的键),它将返回 NULL。这就是文档所说的,这就是我的 PHP 5.2 安装返回的内容。您使用的不是官方内置的json_decode() 的功能吗? var_dump(json_decode($str, true)); 返回什么?
  • 在 json_encoding 之后,我想读取每个单独的 json 对象,例如{foo:"bar"} 作为数组中的一个对象。如何从 json_encoded 数据创建一个数组来读取每个 json 对象? @RikkusRukkus
  • @Manny265 这听起来像是值得自己提出问题的问题(1)一些示例代码,(2)您到目前为止尝试过的内容以及(3)预期的结果,而不是这个评论部分。
【解决方案3】:

如果您使用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】:

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

    正确方法:

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

    【讨论】:

    • 完美,这行得通。当我从 $_POST 函数 json_last_error() 获取数据时 = 到 JSON_ERROR_SYNTAX。但一切都很好。这是解码错误,而不是像 ascii 或 utf8 这样的编码错误。谢谢
    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 它的末尾有一个 true
      【解决方案7】:

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

      https://github.com/mobsted/jsontophparray

      【讨论】:

        【解决方案8】:

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

        【讨论】:

          【解决方案9】:
          <?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);
          
          ?>
          

          我认为这应该可行,只是如果键不是数字,它们也应该用双引号引起来。

          【讨论】:

            【解决方案10】:

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

            【讨论】:

            • 谢谢兄弟...你拯救了我的一天
            【解决方案11】:

            确保字符串采用以下 JSON 格式,类似于:

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

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

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

            【讨论】:

            • 欢迎来到 StackOverflow :-) 社区总是很高兴新成员愿意为它做出贡献并欣赏你的态度。可悲的是,另一位成员认为您的回答值得一票否决。这可能是因为这个问题本身是在大约七年前被问到的,并且已经被回答了好几次。此外,responseType 属性用于确定请求应答中的数据类型。然而问题是,请求正文包含的数据本身并不正确。因此,您的答案不符合给定的上下文。
            【解决方案12】:
            $data = json_encode($result, true);
            
            echo $data;
            

            【讨论】:

            • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
            【解决方案13】:

            您可以按如下方式将字符串更改为 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;
            

            【讨论】:

            • 它返回 [1] 作为 $filter_id 和相同的 json 对象作为 $fiters
            【解决方案14】:

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

            【讨论】:

              【解决方案15】:

              您调用 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>';
              

              【讨论】:

                猜你喜欢
                • 2017-07-20
                • 2015-04-05
                • 2022-01-27
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多