JMeter如何从CSV文件随机选4个值组成数组传入请求体?
从CSV随机选取主题生成指定格式的请求体
需求说明
- 现有CSV文件,每行存储一个独立的兴趣主题
- 需随机选取4个不重复的主题,组成字符串数组
- 生成包含该数组及固定参数的JSON请求体,格式示例:
{"interest":["Mobility Testing", "BI Modernization", "Data Monetization", "Big Data Testing"],"user_id":"8aafa3be-c19b-4355-88cb-1c068463790d","user_id_type":"wid"}
Python实现方案
以下是基于Python基础库的简洁实现,无需额外依赖:
完整代码
import csv import random import json # 读取CSV中的兴趣主题,跳过空行 interests = [] with open('interests.csv', 'r', encoding='utf-8') as csv_file: # 逐行读取并处理主题(假设每行仅包含一个主题) for line in csv_file: topic = line.strip() if topic: # 忽略空行 interests.append(topic) # 随机选取4个不重复的主题 selected_topics = random.sample(interests, 4) # 构造请求体 request_payload = { "interest": selected_topics, "user_id": "8aafa3be-c19b-4355-88cb-1c068463790d", "user_id_type": "wid" } # 转为格式化的JSON字符串(方便查看和使用) formatted_json = json.dumps(request_payload, indent=2) print(formatted_json)
补充说明
去重处理:如果CSV中存在重复主题,可在读取后添加去重逻辑:
interests = list(set(interests)) # 转为集合去重,再转回列表注:去重会打乱原顺序,但不影响随机选取的结果。
发送请求:如果需要直接将请求体发送到目标接口,可使用
requests库(需先安装:pip install requests):import requests api_url = "你的目标接口URL" response = requests.post(api_url, json=request_payload) print(f"请求状态码: {response.status_code}") print(f"响应内容: {response.text}")
内容的提问来源于stack exchange,提问作者Gomathy Balakrishnan
相关产品推荐
相关产品推荐

