1

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?

Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
Mitch Wolfe
  • 139
  • 7
  • It's not really "nested JSON", it's just an object within an object. There's only one JSON encoding going on here. – Brad Jul 03 '18 at 04:56
  • Possible duplicate of [php get values from json encode](https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode) – M. Eriksson Jul 03 '18 at 04:58

1 Answers1

1

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"];
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36