需求
- 根据以下json体,生成230+OrderList对象
- 生成10位有序的数字字母随机数赋值给OrderDetailList.ApiOrderId 和 OrderDetailList.Traceid
- 生成的Json文件 保存在项目JSON目录中
{
"UAccount": "xxxx",
"Password": "",
"Token": "93B4DD39F7F09B99C8",
"OrderList": [{
"CiId": "CO",
"PtId": "COL-CC",
"ReceiverName": "Duván Rodríguez",
"County": "Bogota DC",
"City": "Engativa",
"Zip": "111021",
"Address1": "calle 17A#10C-28",
"Address2": "Hotel La CochinillaA",
"Phone": "703688488",
"Email": "196bed2261f781f44032@members.ebay.com",
"ApiOrderId": "",
"OnlineShopName": "测试小店",
"PackType": 3,
"SalesPlatformFlag": 0,
"SyncPlatformFlag": "scb.logistics.banggood",
"MultiPackageQuantity": 1,
"Traceid": "",
"OrderDetailList": [
{
"ItemName": "Final Fantasy",
"Price": 27.98,
"Quantities": "27"
}
],
"HaikwanDetialList": [
{
"ItemEnName": "Holiday ornament3",
"ItemCnName": "藤条3",
"Quantities": "1",
"HwCode": "392690",
"UnitPrice": 1.85,
"ProducingArea": "CN",
"CCode": "USD",
"Weight": 1.35
}
],
"OrderVolumeWeights": [
{
"WeighingWeight": 0.234
}
]
}]
}
代码
# -*- coding: utf-8 -*-
import json
import random
import string
from pathlib import Path
import copy
def generate_random_id(length=12):
"""生成12位大写字母和数字的随机字符串"""
chars = string.ascii_uppercase + string.digits
return ''.join(random.choices(chars, k=length))
def get_unique_ids(count):
"""生成指定数量的唯一ID集合"""
ids = set()
while len(ids) < count:
ids.add(generate_random_id())
return ids
# 原始模板
template = {
"UAccount": "xxxxx",
"Password": "E10ADCE56E057F20F883E",
"Token": "93B4DD5-AFC6-78F7F09B99C8",
"OrderList": []
}
# 单个订单项模板
order_template = {
"CiId": "CO",
"PtId": "COL-CC",
"ReceiverName": "Duván Rodríguez",
"County": "Bogota DC",
"City": "Engativa",
"Zip": "111021",
"Address1": "calle 17A#10C-28",
"Address2": "Hotel La CochinillaA",
"Phone": "703688488",
"Email": "196bed2261f781f44032@members.ebay.com",
"ApiOrderId": "",
"OnlineShopName": "测试小店",
"PackType": 3,
"SalesPlatformFlag": 0,
"SyncPlatformFlag": "scb.logistics.banggood",
"MultiPackageQuantity": 1,
"Traceid": "",
"OrderDetailList": [
{
"ItemName": "Final Fantasy",
"Price": 27.98,
"Quantities": "27"
}
],
"HaikwanDetialList": [
{
"ItemEnName": "Holiday ornament3",
"ItemCnName": "藤条3",
"Quantities": "1",
"HwCode": "392690",
"UnitPrice": 1.85,
"ProducingArea": "CN",
"CCode": "USD",
"Weight": 1.35
}
],
"OrderVolumeWeights": [
{
"WeighingWeight": 0.234
}
]
}
# 生成460个唯一ID(每个订单项需要两个ID)
unique_ids = list(get_unique_ids(230 * 2))
# 构建230个订单项
order_list = []
for i in range(230):
new_order = copy.deepcopy(order_template)
api_id = unique_ids[i * 2] # ApiOrderId
trace_id = unique_ids[i * 2 + 1] # Traceid
new_order["ApiOrderId"] = api_id
new_order["Traceid"] = trace_id
order_list.append(new_order)
template["OrderList"] = order_list
# 创建目录并保存文件
output_dir = Path("JSON")
output_dir.mkdir(exist_ok=True)
output_path = output_dir / "Batch_Create_Orders.json"
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(template, f, indent=4, ensure_ascii=False)
print(f"文件已生成:{output_path}")
运行结果: