duancan2539
2018-07-03 04:51
浏览 139

在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?

图片转代码服务由CSDN问答提供 功能建议

我试图让python客户端发送一个包含嵌套JSON的帖子请求 {“nested”:{“field1”:“response1”,“field2”:“response2”}}

我的python 代码在这里

  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代码:

 <代码>的print_r($ _ POST [ “嵌套”]); 
   
 
 

返回

 <代码 > {'field2':'response2','field1':'response1'} 
   
 
 

但当我尝试使用$ _POST [“嵌套”访问“field1”时 “] [”field1“],它返回:

  {
   
 
 

而不是返回”response1“ 。 如何让我的代码返回嵌套JSON中的字段?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyong9224 2018-07-03 04:55
    已采纳

    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"];
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题