duancan2539 2018-07-03 04:51
浏览 168
已采纳

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

  • 写回答

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"];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复