-2

Here is the PHP code that I want to write in Python.

<?php

$json = '{
  "targeting": [
    {
      "country": {
        "allow": [
            "US",
            "DE"
        ]
      },
      "region" : {
        "allow" : {
          "US" : [ 
              33
          ],
          "DE" : [ 
              10383
          ]
        }
      },
      "city": {
        "allow": {
          "US": [
            57
          ],
          "DE": [
            3324
          ]
        }
      },
      "os": {
        "allow": [
          {
            "name": "Android",
            "comparison": "GTE",
            "version": "2.3.1"
          },
          {
            "name": "Apple TV Software",
            "comparison": "EQ",
            "version": "4.4"
          },
          {
            "name": "Windows",
            "comparison": "EQ",
            "version": "Vista"
          }
        ]
      },
      "isp" : {
        "allow" : {
          "US" : [ 
              "Att"
          ],
          "DE" : [ 
              "Telekom"
          ]
        }
      },
      "ip": {
        "allow": [
          "11.12.13.0-17.18.19.22",
          "6.0.0.0",
          "10.0.0.0-10.0.0.2",
          "11.0.0.0/24"
        ]
      },
        "device_type": [
        "mobile"
      ],
      "browser": {
        "allow": [
          "Yandex.Browser for iOS",
          "SlimBrowser",
          "Edge Mobile"
        ]
      },
      "brand": {
        "allow": [
          "Smartbook Entertainment",
          "Walton",
          "PIPO"
        ]
      },
      "sub": {
        "allow": {
          "1": [
            "A",
            "B"
          ]
        },
        "deny": {
          "2": [
            "C",
            "D"
          ]
        },
        "deny_groups": [
          {
            "1": ""
          },
          {
            "1": "X",
            "2": "Y"
          }
        ]
      },
      "connection": [
        "wi-fi",
        "cellular"
      ],
      "block_proxy": true,
      "affiliate_id": [
        1
      ],
      "url": "http://test-url.com"
    }
  ]
}';

$arr = json_decode($json);

$postData = http_build_query($arr);
//POST SomeURLhere
echo urldecode($arr);

What I need is to send this json in this format

targeting[0][country][allow][]=TR
targeting[0][os][allow][][name]=iOS
targeting[1][country][allow][]=DE
targeting[1][os][allow][][name]=iOS

I guess I need to figure out how to use http_build_query in Python.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
KKK
  • 109
  • 1
  • 7
  • You tagged this question `python`, so people with knowledge of Python will come here. Not necessarily with PHP knowledge (me included) so maybe instead of phrasing this as a translation question, simply describe what you are trying to do. I personally have no idea what `http_build_query` does... – Tomerikoo Dec 01 '21 at 14:34
  • What it does is converting json to this format ```targeting[0][country][allow][0]=US&targeting[0][country][allow][1]=DE etc.``` – KKK Dec 01 '21 at 15:18

1 Answers1

0

with referring this answer I found the solution.

from collections.abc import MutableMapping
from urllib.parse import urlencode, unquote

def flatten(dictionary, parent_key=False, separator='.', separator_suffix=''):
    """
    Turn a nested dictionary into a flattened dictionary
    :param dictionary: The dictionary to flatten
    :param parent_key: The string to prepend to dictionary's keys
    :param separator: The string used to separate flattened keys
    :return: A flattened dictionary
    """

    items = []
    for key, value in dictionary.items():
        new_key = str(parent_key) + separator + key + separator_suffix if parent_key else key
    if isinstance(value, MutableMapping):
        items.extend(flatten(value, new_key, separator, separator_suffix).items())
    elif isinstance(value, list) or isinstance(value, tuple):
        for k, v in enumerate(value):
            items.extend(flatten({str(k): v}, new_key, separator, separator_suffix).items())
    else:
        items.append((new_key, value))
return dict(items)


req = {'check': 'command', 'parameters': ({'parameter': '1', 'description': 
'2'}, {'parameter': '3', 'description': '4'})}
req = flatten(req, False, '[', ']')
query = urlencode(req)
query_parsed = unquote(query)
print(query)
print(query_parsed)

And the outputs:

check=command&parameters%5B0%5D%5Bparameter%5D=1&parameters%5B0%5D%5Bdescription%5D=2&parameters%5B1%5D%5Bparameter%5D=3&parameters%5B1%5D%5Bdescription%5D=4
check=command&parameters[0][parameter]=1&parameters[0][description]=2&parameters[1][parameter]=3&parameters[1][description]=4
KKK
  • 109
  • 1
  • 7
  • Is this solution still working? The indentation of the last return statement is wrong obviously but still when fixing this little issue, I get not printed output. I now understood that you basically copy pasted the solution from the original post you mentioned but apparently introduced some issues in the code. Maybe you should fix that? – TheDude Mar 11 '22 at 08:17