php 如何将 JSON 字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7511821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert JSON string to array
提问by XMen
What I want to do is the following:
我想要做的是以下内容:
- taking JSON as input from text area in php
- use this input and convert it to JSON and pass it to php curl to send request.
- 将 JSON 作为来自 php 文本区域的输入
- 使用此输入并将其转换为 JSON 并将其传递给 php curl 以发送请求。
this m getting at php from get of api this json string i want to pass to json but it is not converting to array
这我从 api 获取这个 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);
the above code is not returning me array.
上面的代码没有返回我的数组。
回答by RickN
If you pass the JSON in your post to json_decode
, it will fail. Valid JSON strings have quoted keys:
如果您将帖子中的 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.
回答by sepidol
Try this:
尝试这个:
$data = json_decode($your_json_string, TRUE);
the second parameter will make decoded json string into an associative arrays.
第二个参数将解码的 json 字符串转换为关联数组。
回答by jbeauchamp
If you are getting the JSON string from the form using $_REQUEST
, $_GET
, or $_POST
the you will need to use the function html_entity_decode()
. I didn't realize this until I did a var_dump
of what was in the request vs. what I copied into and echo
statement and noticed the request string was much larger.
如果你是从形式获取JSON字符串使用$_REQUEST
,$_GET
或者$_POST
在您需要使用的功能html_entity_decode()
。我没有意识到这一点,直到我做了var_dump
请求中的内容与我复制到和echo
语句中的内容并注意到请求字符串大得多。
Correct Way:
正确方法:
$jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);
With Errors:
有错误:
$jsonText = $_REQUEST['myJSON'];
$myArray = json_decode($jsonText, true);
echo json_last_error(); //Returns 4 - Syntax error;
回答by Arslan Ramay
Use json_decode($json_string, TRUE)
function to convert the JSON object to an array.
使用json_decode($json_string, TRUE)
函数将 JSON 对象转换为数组。
Example:
例子:
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$my_array_data = json_decode($json_string, TRUE);
NOTE: The second parameter will convert decoded JSON string into an associative array.
注意:第二个参数将解码的 JSON 字符串转换为关联数组。
===========
============
Output:
输出:
var_dump($my_array_data);
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
回答by Dinanath Thakur
your string should be in the following format:
您的字符串应采用以下格式:
$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);
Output:
输出:
Array
(
[action] => create
[record] => Array
(
[type] => n$product
[fields] => Array
(
[n$name] => Bread
[n$price] => 2.11
)
[namespaces] => Array
(
[my.demo] => n
)
)
)
回答by piyush
If you are getting json string from URL using file_get_contents
, then follow the steps:
如果您使用从 URL 获取 json 字符串file_get_contents
,请按照以下步骤操作:
$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));
回答by Manav Akela
You can convert json Object into Array & String.
您可以将 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++;
}
回答by Shahrukh Anwar
You can change a string to JSON as follows and you can also trim, strip on string if wanted,
您可以按如下方式将字符串更改为 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;
回答by Pradeep Dhawan
<?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);
?>
i think this should Work, its just that the Keys should also be in double quotes if they are not numerals.
我认为这应该有效,只是如果键不是数字,它们也应该用双引号引起来。
回答by Mourad MAMASSI
this my solution:
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 字符串 $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}]"
so i use json_decode twice like that :
所以我这样使用 json_decode 两次:
$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation);
var_dump($js_column_validation);
and the result is :
结果是:
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 }