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

如何用Python为含千余字段的JSON生成随机唯一值

用Python替换JSON空值为随机唯一字符串

以下是完整的解决方案,针对你的需求处理嵌套JSON结构中的所有空字符串:

完整代码

import json
import secrets
import string

def generate_random_str(length=10):
    # 生成由大写字母组成的随机字符串,可自定义字符集和长度
    char_set = string.ascii_uppercase
    return ''.join(secrets.choice(char_set) for _ in range(length))

def replace_empty_fields(data, used_values=None):
    if used_values is None:
        used_values = set()
    
    # 处理字典类型
    if isinstance(data, dict):
        for key, value in data.items():
            if value == "":
                # 生成唯一随机字符串(避免重复)
                while True:
                    rand_str = generate_random_str()
                    if rand_str not in used_values:
                        used_values.add(rand_str)
                        data[key] = rand_str
                        break
            else:
                # 递归处理嵌套结构
                replace_empty_fields(value, used_values)
    # 处理列表类型
    elif isinstance(data, list):
        for item in data:
            replace_empty_fields(item, used_values)
    
    return data

# ---------------------- 使用示例 ----------------------
# 1. 从字符串加载JSON(如果是文件,用open读取)
input_json = '''
{
  "Order": {
    "AdjustmentInvoicePending": "",
    "AllAddressesVerified": "",
    "AllocationRuleID": "",
    "AuthorizationExpirationDate": "",
    "BillToKey": "",
    "CarrierAccountNo": "",
    "ChainType": "",
    "ChargeActualFreightFlag": "",
    "ComplimentaryGiftBoxQty": "",
    "ContactKey": "",
    "CustomerAge": "",
    "CustomerEMailID": "",
    "CustomerFirstName": "",
    "CustomerLastName": "",
    "CustomerPhoneNo": "",
    "CustomerZipCode": "",
    "Division": "",
    "DocumentType": "",
    "DraftOrderFlag": "",
    "EnterpriseCode": "",
    "EntryType": "",
    "FreightTerms": "",
    "HasDeliveryLines": "",
    "HasDerivedChild": "",
    "HasDerivedParent": "",
    "HasProductLines": "",
    "HoldFlag": "",
    "HoldReasonCode": "",
    "InvoiceComplete": "",
    "isHistory": "",
    "MaxOrderStatus": "",
    "MaxOrderStatusDesc": "",
    "MinOrderStatus": "",
    "MinOrderStatusDesc": "",
    "NoOfAuthStrikes": "",
    "NotifyAfterShipmentFlag": "",
    "OrderClosed": "",
    "OrderDate": "",
    "OrderHeaderKey": "",
    "OrderNo": "",
    "OrderType": "",
    "OriginalTax": "",
    "OriginalTotalAmount": "",
    "OtherCharges": "",
    "PaymentRuleId": "",
    "PaymentStatus": "",
    "PendingTransferIn": "",
    "PriorityNumber": "",
    "ReqCancelDate": "",
    "ReturnByGiftRecipient": "",
    "SaleVoided": "",
    "ScacAndService": "",
    "ScacAndServiceKey": "",
    "SellerOrganizationCode": "",
    "ShipToKey": "",
    "SourcingClassification": "",
    "Status": "",
    "Tax": "",
    "TotalAdjustmentAmount": "",
    "AdditionalAddresses": {
      "AdditionalAddress": [
        {
          "AddressType": "",
          "EntityKey": "",
          "PersonInfoKey": "",
          "PersonInfo": {
            "AddressID": "",
            "AddressLine1": "",
            "AddressLine2": "",
            "AddressLine3": "",
            "AddressLine4": "",
            "AddressLine5": "",
            "AddressLine6": "",
            "AddressType": "",
            "AlternateEmailID": "",
            "Beeper": "",
            "City": "",
            "Company": "",
            "Country": "",
            "DayFaxNo": "",
            "DayPhone": "",
            "Department": "",
            "EMailID": "",
            "EveningFaxNo": "",
            "EveningPhone": "",
            "FirstName": "",
            "IsAddressVerified": "",
            "IsCommercialAddress": "",
            "JobTitle": "",
            "LastName": "",
            "Latitude": "",
            "Longitude": "",
            "MiddleName": "",
            "MobilePhone": "",
            "OtherPhone": "",
            "PersonID": "",
            "PersonInfoKey": "",
            "State": "",
            "Suffix": "",
            "TaxGeoCode": "",
            "Title": "",
            "ZipCode": ""
          }
        }
      ]
    }
}
'''

# 解析JSON为Python字典
json_data = json.loads(input_json)

# 替换所有空字段
modified_data = replace_empty_fields(json_data)

# 转换回格式化的JSON字符串
output_json = json.dumps(modified_data, indent=2)

# 打印结果或写入文件
print(output_json)
# with open('output.json', 'w') as f:
#     json.dump(modified_data, f, indent=2)

关键说明

  1. 随机字符串生成:使用secrets模块生成安全的随机值,比random更适合生成不可预测的字符串。默认生成10位大写字母,可修改generate_random_str函数调整字符集(如加入数字)或长度。
  2. 递归遍历:replace_empty_fields函数会遍历所有嵌套的字典和列表,确保每个空字符串都被替换。通过used_values集合保证生成的随机值在整个JSON中唯一。
  3. 文件处理:如果你的JSON存储在文件中,将input_json替换为open('your_file.json', 'r').read()即可。修改后的结果可通过json.dump写入新文件。

可选优化

  • 若不需要严格的唯一性(仅需每次运行生成不同值),可去掉used_values的循环检查,直接生成随机字符串,提升处理速度。
  • 针对特定字段类型生成对应格式的值:比如CustomerAge生成随机整数,CustomerEMailID生成xxx@example.com格式的字符串,可在替换逻辑中添加字段名判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:16:14