You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP http_build_query的Python等效实现,嵌套JSON转指定格式表单查询串

PHP http_build_query功能的Python实现方案

你需要实现的嵌套结构转PHP风格查询字符串功能,有两种常用实现方式:

方案1:使用第三方对齐实现(推荐,100%兼容PHP行为)

直接使用PyPI上专门兼容PHP http_build_query 的第三方包,无需自行处理嵌套逻辑:

  • 安装依赖:
pip install php-http-build-query
  • 完整代码示例:
import json
from php_http_build_query import http_build_query

# 你提供的JSON结构
json_str = '''
{
  "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"
    }
  ]
}
'''

# 加载JSON为Python字典
data = json.loads(json_str)
# 生成和PHP完全一致的查询字符串
query_str = http_build_query(data)

# 如果需要查看urldecode后的格式,直接输出即可
print(query_str)

# 用于POST请求的话,直接传给requests即可
import requests
response = requests.post("你的请求地址", data=query_str, headers={"Content-Type": "application/x-www-form-urlencoded"})

方案2:原生Python自实现(无需第三方依赖)

如果不想安装额外包,可以自己实现递归展平嵌套结构的逻辑,再用原生urllib编码:

import json
import urllib.parse

def flatten_php_style(data, parent_key=''):
    items = []
    if isinstance(data, dict):
        for k, v in data.items():
            new_key = f"{parent_key}[{k}]" if parent_key else k
            items.extend(flatten_php_style(v, new_key).items())
    elif isinstance(data, list):
        for i, v in enumerate(data):
            new_key = f"{parent_key}[]" if isinstance(v, (dict, list)) else f"{parent_key}[{i}]"
            items.extend(flatten_php_style(v, new_key).items())
    else:
        items.append((parent_key, data))
    return dict(items)

# 加载JSON
data = json.loads(json_str)
# 展平结构
flatten_data = flatten_php_style(data)
# 生成查询字符串
query_str = urllib.parse.urlencode(flatten_data)
print(query_str)

注意:自实现版本仅覆盖常规嵌套场景,如果有非常特殊的边缘需求建议使用方案1的第三方兼容包。


内容的提问来源于stack exchange,提问作者KKK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:36:02