在PHP中处理嵌套的JSON POST请求
I am trying to have a python client send a post request which contains nested JSON like such
{"nested":{"field1":"response1", "field2":"response2"}}
My python code is here
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url="http://localhost/api/vscore.php"
post_fields={"nested":{"field1":"response1", "field2":"response2"}}
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
PHP code:
print_r($_POST["nested"]);
returns
{'field2': 'response2', 'field1': 'response1'}
but when I try to access "field1" with $_POST["nested"]["field1"], it returns this:
{
instead of returning "response1". How can I get my code to return fields in nested JSON?
我试图让python客户端发送一个包含嵌套JSON的帖子请求 p>
我的python 代码在这里 p>
PHP代码: p>
返回 p>
但当我尝试使用$ _POST [“嵌套”访问“field1”时 “] [”field1“],它返回: p>
而不是返回”response1“ 。 如何让我的代码返回嵌套JSON中的字段? p>
div> {“nested”:{“field1”:“response1”,“field2”:“response2”}}
code> pre>
from urllib.parse import urlencode
from urllib.request import Request,urlopen
url =“http: //localhost/api/vscore.php"
post_fields={"nested":{"field1":"response1“,”field2“:”response2“}}
request = Request(url,urlencode(post_fields)。 encode())
json = urlopen(request).read()。decode()
print(json)
code> pre>
的print_r($ _ POST [ “嵌套”]);
代码> PRE>
{'field2':'response2','field1':'response1'}
code> pre>
{
code> pre>
If request is in json form then, you should json_decode it first and then try to access. nested
key should be accessed as:
$nested = json_decode($_POST["nested"], true);
$field = $nested["field1"];