簡體   English   中英

在 PHP 中處理嵌套的 JSON POST 請求

[英]Handling nested JSON POST requests in PHP

我正在嘗試讓 python 客戶端發送一個 post 請求,其中包含像這樣的嵌套 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["nested"]);

返回

{'field2': 'response2', 'field1': 'response1'}

但是當我嘗試使用 $_POST["nested"]["field1"] 訪問“field1”時,它返回:

{

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

如果請求是 json 形式,則應先將json_decode再嘗試訪問。 nested鍵應該被訪問為:

$nested = json_decode($_POST["nested"], true);
$field = $nested["field1"];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM