繁体   English   中英

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

[英]How to convert JSON string to array

我想要做的是:

  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 传递给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.

尝试这个:

$data = json_decode($your_json_string, TRUE);

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

如果您使用$_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;

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

如果您使用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));

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

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

        )

)

您可以将 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++;
}

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

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

?>

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

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

所以我这样使用 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 }

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

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

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

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

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

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

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

如果要转换为对象,则 $data = json_decode($yourJson);

如果要转换为数组,则 $data = json_decode($yourJson,TRUE);

您可以使用它来获取 JSON 数据的 object,方法是在解码数据之前将其设置为 object。 这仅在您将 object 作为 JSON 字符串发送时有效

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

$data = json_encode($result, true);

echo $data;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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