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

我想做的是:

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

这个字符串我想传递给 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);

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

633197 次浏览

试试这个:

$data = json_decode($your_json_string, TRUE);

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

如果您将文章中的 JSON 传递给 json_decode,它将失败:

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.

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

如果使用 $_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)
}

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

$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 文件或结构转换为具有所有嵌套级别的 PHP 样式的数组,可以使用此函数。首先,必须使用 json _ decode ($yourJSONdata) ,然后将其传递给这个函数。它会将正确的 PHP 样式的数组输出到浏览器窗口(或控制台)。

Https://github.com/mobsted/jsontophparray

使用这个转换器,它不会失败: 服务 _ 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);
<?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 字符串 $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,如果需要,还可以对字符串进行修剪、剥离,

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

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

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

这应该工作,只是钥匙也应该在双引号,如果他们不是数字。

产出:-

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


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

它将把 Json String 转换为 Array

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

$data = json_decode($yourJson);

如果你想转换成一个数组,那么:

$data = json_decode($yourJson,TRUE);