-
为什么要用 JSON 提取器JSON 是目前大多数接口响应内容的数据格式在接口测试中,不同接口之间可能会有数据依赖,在 Jmeter 中可以通过后置处理器来提取接口的响应内容JSON 提取器是其中一个可以用来提取响应内容的元件 JSON 提取器的应用场景提取某个特定的值提取多个值按条件取值提取值组成的列表 JSON 提取器我们通过实际栗子去讲述理论知识点 JSON 提取器界面介绍 字段含义 字段结果Apply to应用范围,选默认的 main sample only 就行了Names of created variables接收提取值的变量名多个变量用 ; 分隔必传JSON Path expressionjson path 表达式,用来提取某个值多个表达式用 ; 分隔必传Match No.(0 for Random)取第几个值,多个值用 ; 分隔0:随机,默认-1:所有1:第一个值非必传Compute concatenation var(suffix_ALL)如果匹配到多个值,则将它们都连接起来,不同值之间用 , 分隔变量会自动命名为 <variable name>_ALL Default Values缺省值,匹配不到值的时候取该值,可写error多个值用 ; 分隔非必传 入门栗子 测试计划树结构下面多个栗子都以这个测试计划为基础哦 提取某个特定的值的栗子登录接口响应登录是执行其他接口的前置接口,所以要获取用户登录后的 token、uuid 提取 token相对路径的方式 提取 uuid绝对路径的方式 其他接口调用 token、uuid 知识点提取某个特定值的方式有两种:绝对路径、相对路径提其他接口可以通过 ${var} 这种格式,来获取提取到的值 综合栗子上面讲的是使用 JSON 提取器时的一个流程在实际项目中,接口的响应内容肯定是非常复杂的,而我们需要提取的值也是多样化的,需要通过各种实战栗子来讲述清晰 JSON 字符串{ "ret": 200, "msg": "V2.5.1 YesApi App.User.GetList", "data": { "total": 3, "err_msg": "", "err_code": 0, "users": [ { "role": "user", "status_desc": "正常", "reg_time": "2020-06-22 15:19:51", "role_desc": "普通会员", "ext_info": { "yesapi_nickname": "", "yesapi_points": 0 }, "uuid": "6D5EDCB459F0917A98106E07D5438C58", "username": "fangjieyaossb", "status": 0 }, { "role": "user", "status_desc": "正常", "reg_time": "2020-06-22 14:27:17", "role_desc": "普通会员", "ext_info": { "yesapi_nickname": "", "yesapi_points": 0 }, "uuid": "0164DC0680F84DCE40D3DD4A36640ECA", "username": "fangjieyaossa", "status": 0 }, { "role": "admin", "status_desc": "正常", "reg_time": "2020-03-23 22:48:32", "role_desc": "管理员", "ext_info": { "yesapi_nickname": "", "yesapi_points": 0 }, "uuid": "079BF6BB82AFCFC7084F96AECAF0519F", "username": "fangjieyaoss", "status": 0 } ] } } 提取单个值Jsonpath结果$.data.total3$..total3$..users[0].roleuser$..uuid079BF6BB82AFCFC7084F96AECAF0519F$.data.users[0].ext_info.yesapi_points0 重点如果匹配到多个值(像 $..uuid ),也只能提取到一个值如果想提取匹配到的所有 uuid,可以设置为 -1,结果如下图还会告诉你匹配了多少个值 ${uuid_matchNr} ,记住,调用变量时,不再是 ${uuid} 而是 ${uuid_1} 、 ${uuid_2} 利用切片提取单个值和 Python 切片一样的原理Jsonpath结果$..users[2]第三个 users$..users[-2]倒数第二个users$..users[0,1]前面两个users$..users[:2]第一、二个users$..users[1:2]第二个users$..users[-2:]倒数两个users$..users[1:]第二个开始的所有users 提取多个值四种写法类似,选一种方法自己熟记即可重点:提取多个值,提取器的 Match No. 必须填 -1 $.data.users[*].role提取所有 role 字段值[*] 表示取数组的所有元素 $..users..role_desc提取所有 role_desc 字段值 $..reg_time提取所有 reg_time 字段值 $..[*].username提取所有 username 字段值 按条件提取值有时候只需要提取某个特定条件下的参数值 语法格式[?(expression)] 栗子Jsonpath结果$..users[?(@.uuid)]提取 users 里面包含 uuid 字段的记录$..users[?(@.reg_time > '2020-06-01')]提取 reg_time 字段大于 2020-06-01 的记录$..users[?(@.role_desc =~ /.*会员.*?/i)]提取 role_desc 字段包含会员的记录$..users[?(@.status == 0)]提取 status 字段等于 0 的记录 @代表当前节点,像上面的四个栗子,@代表 users 这个列表字段 =~后面跟正则表达式,如果想提取包含指定字符的值,可以使用此正则: /.*指定字符串.*?/i i 代表大小写不敏感 提取数据指定字段的值的栗子提取 users 第一条记录的 uuid、username 字段的值$..users[0].['uuid','username'] 测试结果new_1={"uuid":"6D5EDCB459F0917A98106E07D5438C58","username":"luojunjiessb"} 勾选 Compute concatenation var 的栗子JSON 提取器 测试结果uuid_1=6D5EDCB459F0917A98106E07D5438C58 uuid_2=0164DC0680F84DCE40D3DD4A36640ECA uuid_3=079BF6BB82AFCFC7084F96AECAF0519F uuid_ALL=6D5EDCB459F0917A98106E07D5438C58,0164DC0680F84DCE40D3DD4A36640ECA,079BF6BB82AFCFC7084F96AECAF0519F uuid_matchNr=3 一个 JSON 提取器有多个 Jsonpath 的栗子JSON 提取器 测试结果uuid1_1=6D5EDCB459F0917A98106E07D5438C58 uuid1_2=0164DC0680F84DCE40D3DD4A36640ECA uuid1_3=079BF6BB82AFCFC7084F96AECAF0519F uuid1_matchNr=3 uuid2_1=6D5EDCB459F0917A98106E07D5438C58 uuid2_2=0164DC0680F84DCE40D3DD4A36640ECA uuid2_3=079BF6BB82AFCFC7084F96AECAF0519F uuid2_matchNr=3
-
【功能模块】ReduceSum输入要求如下:*@li x: A Tensor. Must be one of the following types:* float32, float64, int32, uint8, int16, int8,* complex64, int64, qint8, quint8, qint32, uint16,* complex128, float16, uint32, uint64, complex64, complex128.*@li axes: A 1D list or tuple of int32 or int64. Specifies the dimensions to reduce . 【操作步骤&问题现象】第二个输入是含有多个元素的数组时(元素的值不能重复,且元素的值要人为指定,因为输出的shape和元素的取值有关),按照链接 https://support.huaweicloud.com/aicpu_devg_community_beta/atlasaicpu_10_0030.html 不知道该如何编写
-
GetResultGetResult或GetResultWithUniqueId拿到的是经过序列化插件后的结果,形成一个json字符串。示例:inferResult = streamManagerApi.GetResultWithUniqueId(streamName, uniqueId, 3000)1.首先将其转为一个json对象:res_dict = json.loads(inferResult.data.decode())2.之后按照读取字典成员的方法,找到所需的内存对应的序列化后字符串:具体读取方法与pipeline有关,如下仅作示例参考。res = res_dict["MxpiVision"][0]["visionData"]["dataStr"]3.最后用base64的库将序列化后字符串解码回来,并用numpy读取。n = np.frombuffer(base64.b64decode(res), dtype=np.uint8)4.运行成功:print("tensor:", n)print("tensor shape:", n.shape)GetProtobufGetProtobuf拿到的经过protobuf序列化后的字符串,内存没有经过base64编码,相对上一种,转换回来更加简单。示例:keyVec = StringVector()keyVec.push_back(b'mxpi_tensorinfer0')inferResult = streamManagerApi.GetProtobuf(streamName, 0, keyVec)1.首先将结果反序列回protobuf:result = MxpiDataType.MxpiTensorPackageList()result.ParseFromString(inferResult[0].messageBuf)2.之后就可以直接读取其内存res = np.frombuffer(result.tensorPackageVec[0].tensorVec[0].dataStr, dtype=np.float32)3.运行成功: print("output tensor is: ",res) print("output tensor shape is: ",res.shape)
-
问题1:之前使用CAN 2.0发消息,今天更新透传时,不小心下发了CAN-FD的透传配置。导致之前CAN 2.0的失效。是否时当前CANFD配置文件与CAN配置文件不能同时存在?如何清除CANFD的配置文件/配置表。问题2:使用MMC配置数据透传后,生成arxml文件会最终生成per_manifest.json,那么是使用devmTool能让这个per_manifest.json生效吗?另外,canbus_config.json和per_manifest.json是什么关系?我使用上传per_manifest.json到MDC后,使用devmTool工具 set-dev-cfg 0后,提示success。但是vi canbus_config.json后,看到canbus_config.json没有改变。请华为的同事尽快回复,感谢!Teacher Tony 发表于2021-04-29 16:09:19 2021-04-29 16:09:19 最后回复 Teacher Tony 2021-04-29 18:47:461037 4
-
【功能模块】配置canfdbus_config.json文件下发出错【操作步骤&问题现象】1、登录mdc用户切换home/mdc/bin2、./devmTool.sh get-dev-cfg 1通过devm工具下发canfdbus_config.json配置文件时出错【截图信息】【日志信息】(可选,上传日志内容或者附件)
-
GetProtobuf可以从sdk的stream中取出指定key的protobuf数据,但是有人在保存json的时候遇到了一个问题,当protobuf的值为默认值的时候(一般是0),该属性直接被忽略没有被保存下来。inferResult = streamManagerApi.GetProtobuf(streamName, 0, keyVec)result = MxpiDataType.MxpiTensorPackageList()result.ParseFromString(inferResult[0].messageBuf)print("message:", result)with open("res.json", 'w') as f: f.write(MessageToJson(result))如下图的classId:其实,并不是sdk返回的结果有问题,而是protobuf本身将默认值设为了不显示。因此,只需要配置一个参数including_default_value_fields就可以成功显示所有默认值。inferResult = streamManagerApi.GetProtobuf(streamName, 0, keyVec)result = MxpiDataType.MxpiTensorPackageList()result.ParseFromString(inferResult[0].messageBuf)print("message:", result)with open("res.json", 'w') as f: f.write(MessageToJson(result, including_default_value_fields=True))修改后:
-
【功能模块】单算子ATC模型转换功能【操作步骤&问题现象】1、在/usr/local/Ascend/ascend-toolkit/latest/acllib/sample/acl_execute_op/acl_execute_gemm/run/out路径下新建文件夹“op_models”2、退出到/usr/local/Ascend/ascend-toolkit/latest/acllib/sample/acl_execute_op/acl_execute_gemm路径3、输入atc --singleop=run/out/test_data/config/gemm.json --soc_version=Ascend310 --output=run/out/op_models指令进行模型转换【截图信息】【日志信息】(可选,上传日志内容或者附件)
-
【功能模块】【操作步骤&问题现象】1、单算子json配置文件在用atc转换离线模型的不支持NDHWC2、我想写一个Conv3D单算子,利用单算子json文件转化成离线模型,结果提示不支持这种输入格式【截图信息】把format换成ND以后,结果又提示输入数据必须要用NDHWC
-
Mysql将查询结果集转换为JSON数据 前言学生表学生成绩表查询单个学生各科成绩(转换为对象JSON串并用逗号拼接)将单个学生各科成绩转换为数组JSON串将数组串作为value并设置key两张表联合查询(最终SQL,每个学生各科成绩)最终结果学生表CREATE TABLE IF NOT EXISTS `student`( `id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(100) NOT NULL PRIMARY KEY ( `id` ))ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO student( id, name ) VALUES ( 1, '张三' );INSERT INTO student( id, name ) VALUES ( 2, '李四' );学生成绩表CREATE TABLE IF NOT EXISTS `score`( `id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(100) NOT NULL `student_id` INT(100) NOT NULL, `score` VARCHAR(100) NOT NULL PRIMARY KEY ( `id` ))ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO score( id, name, student_id, score) VALUES ( 1, '数学', 1, '95.5' );INSERT INTO score( id, name, student_id, score) VALUES ( 2, '语文', 1, '99.5' );INSERT INTO score( id, name, student_id, score) VALUES ( 3, '数学', 2, '95.5' );INSERT INTO score( id, name, student_id, score) VALUES ( 4, '语文', 2, '88' );查询单个学生各科成绩(转换为对象JSON串并用逗号拼接)SELECT GROUP_CONCAT(JSON_OBJECT( 'id',id,'name',name,'student_id',student_id, 'score', score)) as scores FROM scroe where student_id = 1;## 查询结果## {"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}将单个学生各科成绩转换为数组JSON串SELECT CONCAT('[', GROUP_CONCAT(JSON_OBJECT( 'id',id,'name',name,'student_id',student_id, 'score', score)), ']') as scores FROM scroe where student_id = 1## 查询结果## [{"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}]将数组串作为value并设置keySELECT CONCAT('{"scoreData":[', GROUP_CONCAT(JSON_OBJECT( 'id',id,'name',name,'student_id',student_id, 'score', score)), ']}') as scores FROM scroe where student_id = 1## 查询结果## {"scoreData": [{"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}]}两张表联合查询(最终SQL,每个学生各科成绩)SELECT id, name,(SELECT CONCAT('[', GROUP_CONCAT(JSON_OBJECT( 'id',id,'name',name,'student_id',student_id, 'score', score)), ']') as scores FROM scroe WHERE student_id = stu.id) AS scoresfrom student stu## [{"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}]最终结果1张三[{“id”: 1, “name”: “数学”, “student_id”: 1, “score”: “95.5”},{“id”: 2, “name”: “语文”, “student_id”: 1, “score”: “99.5”}]2李四[{“id”: 3, “name”: “数学”, “student_id”: 1, “score”: “95.5”},{“id”:4, “name”: “语文”, “student_id”: 1, “score”: “88”}]
-
【功能模块】Notebook 【操作步骤&问题现象】1、脚本在ModelArts notebook中 调用SDK完成批量Ocr身份证9要素的识别和获取。#!/usr/bin/python3# encoding:utf-8import jsonimport base64import requests# import toolsfrom colorama import initfrom configparser import ConfigParserinit(autoreset=True)# from HWOcrClientAKSK import HWOcrClientAKSKfrom HWOcrClientToken import HWOcrClientTokendef ocr(): username = "xxxxxx" password = "xxxxxx" domain_name = "xxxxxx" # If the current user is not an IAM user, the domain_name is the same as the username. region = "cn-north-4" # cn-north-1,cn-east-2 etc. # req_uri = "/v1.0/ocr/id-card" req_uri = "/v2/056e1bb6468025122f3dc00e0e665453/ocr/id-card" # req_uri = "/v2/056e1bb6468025122f3dc00e0e665453/ocr/auto-classification" # img = "./data/id-card-demo.jpg" # File path or URL of the image to be recognized. path = './data/' print("文件名: " + path) # 二进制方式打开图片文件 f = path # f = open(path+"\\"+filename, 'rb') # img = base64.b64encode(f.read()).decode("utf-8") # params = {"id_card_side":"front","image":img} # request_url = request_url + "?access_token=" + access_token # headers = {'content-type': 'application/x-www-form-urlencoded'} option = {} option["side"] = "front" # payload = {"image": img} # try: ocrClient = HWOcrClientToken(domain_name, username, password, region) response = ocrClient.request_ocr_service_base64(req_uri, f, option) if response.json(): print(response.json()) if 'result' not in response.json().keys(): return name = response.json()["result"]["name"] sex = response.json()["result"]["sex"] nation = response.json()["result"]["ethnicity"] birth = response.json()["result"]["birth"] num = response.json()["result"]["address"] # address = response.json()["error_code"]["AIS.0104"] address = response.json()["result"]["number"] print("姓名:" + name) print("身份证号码:" + num) #tools.sheet_append(name, sex, nation, birth, num, address, filename) else: print("识别错误") #tools.sheet_append(name="识别错误", sex="", nation="", birth="", num="", address="", filename=filename) print("\033[32m-----------------------------------")if __name__ =="__main__": ocr()错误:文件名: ./data//home/ma-user/anaconda3/envs/TensorFlow-1.13.1/lib/python3.6/site-packages/urllib3/connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)Token obtained successfully. [Errno 21] Is a directory: './data/'---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-2-c7099533fc21> in <module>() 55 56 if __name__ =="__main__":---> 57 ocr()<ipython-input-2-c7099533fc21> in ocr() 35 ocrClient = HWOcrClientToken(domain_name, username, password, region) 36 response = ocrClient.request_ocr_service_base64(req_uri, f, option)---> 37 if response.json(): 38 print(response.json()) 39 if 'result' not in response.json().keys():AttributeError: 'NoneType' object has no attribute 'json'【截图信息】【日志信息】(可选,上传日志内容或者附件)代码目录:apig_sdk3 days ago data3 days ago Untitled1.ipynbRunning6 minutes ago9.79 kBapisettings.py3 days ago2.32 kBAutoClassificationDemo.py3 days ago4.97 kBHWOcrClientToken.py3 days ago6.14 kBocr.py3 days ago1.97 kBtools.py
-
SpatialTransformerDFunction spatial transformer ..Inputs:x: A Tensor dtype of float16, float32.theta: A Tensor dtype of float16, float32, auxiliary coefficients .Attributes:output_size: A tuple output size.default_theta: A tuple default thetause_default_theta: List use default thetaalign_corners: Align cornersOutputs:y: A Tensor dtype of float16, float32, should be same shape and type as x.以上是算子清单的介绍,哪里可以查到各个参数的format、shape?我下面的json可以转出来,但运行不对:[{ "op": "SpatialTransformerD", "input_desc": [ { "format": "NCHW", "shape": [1, 3, 360, 640], "type": "float" }, { "format": "ND", "shape": [1, 6], "type": "float" } ], "output_desc": [ { "format": "NCHW", "shape": [1, 3, 360, 640], "type": "float" } ], "attr": [ { "name": "output_size", "type": "list_int", "value": [1, 3, 360, 640] }, { "name": "default_theta", "type": "list_float", "value": [1, 1, 1, 1, 1, 1] }, { "name": "use_default_theta", "type": "bool", "value": true }, { "name": "align_corners", "type": "list_bool", "value": [false] } ]}]
-
一、Json和struct互换(1)Json转struct例子:1234567891011121314151617181920212223242526package main import ( "fmt" "encoding/json") type People struct { Name string `json:"name_title"` Age int `json:"age_size"`} func JsonToStructDemo(){ jsonStr := ` { "name_title": "jqw" "age_size":12 } ` var people People json.Unmarshal([]byte(jsonStr), &people) fmt.Println(people)} func main(){ JsonToStructDemo()}输出:注意json里面的key和struct里面的key要一致,struct中的key的首字母必须大写,而json中大小写都可以。(2)struct转json在结构体中引入tag标签,这样匹配的时候json串对应的字段名需要与tag标签中定义的字段名匹配,当然tag中定义的名称不需要首字母大写,且对应的json串中字段名仍然大小写不敏感。此时,结构体中对应的字段名可以不用和匹配的一致,但是首字母必须大写,只有大写才是可对外提供访问的。例子:123456789101112131415161718192021222324252627package main import ( "fmt" "encoding/json") type People struct { Name string `json:"name_title"` Age int `json:"age_size"`} func StructToJsonDemo(){ p := People{ Name: "jqw", Age: 18, } jsonBytes, err := json.Marshal(p) if err != nil { fmt.Println(err) } fmt.Println(string(jsonBytes))} func main(){ StructToJsonDemo()}输出:二、json和map互转(1)json转map例子:1234567891011121314func JsonToMapDemo(){ jsonStr := ` { "name": "jqw", "age": 18 } ` var mapResult map[string]interface{} err := json.Unmarshal([]byte(jsonStr), &mapResult) if err != nil { fmt.Println("JsonToMapDemo err: ", err) } fmt.Println(mapResult)}输出:(2)map转Json例子123456789101112func MapToJsonDemo1(){ mapInstances := []map[string]interface{}{} instance_1 := map[string]interface{}{"name": "John", "age": 10} instance_2 := map[string]interface{}{"name": "Alex", "age": 12} mapInstances = append(mapInstances, instance_1, instance_2) jsonStr, err := json.Marshal(mapInstances) if err != nil { fmt.Println("MapToJsonDemo err: ", err) } fmt.Println(string(jsonStr))}输出:例2:1234func MapToJsonDemo2(){ b, _ := json.Marshal(map[string]int{"test":1, "try":2}) fmt.Println(string(b))}输出:三、map和struct互转(1)map转struct需要安装一个第三方库在命令行中运行:go get github.com/goinggo/mapstructure例子:123456789101112func MapToStructDemo(){ mapInstance := make(map[string]interface{}) mapInstance["Name"] = "jqw" mapInstance["Age"] = 18 var people People err := mapstructure.Decode(mapInstance, &people) if err != nil { fmt.Println(err) } fmt.Println(people)}输出(2)struct转map例子123456789101112131415func StructToMapDemo(obj interface{}) map[string]interface{}{ obj1 := reflect.TypeOf(obj) obj2 := reflect.ValueOf(obj) var data = make(map[string]interface{}) for i := 0; i < obj1.NumField(); i++ { data[obj1.Field(i).Name] = obj2.Field(i).Interface() } return data}func TestStructToMap(){ student := Student{10, "jqw", 18} data := StructToMapDemo(student) fmt.Println(data)}输出:
-
【功能模块】在IOT物联网全栈成长计划第三阶段,模拟自动售货机形成的数据经过整合后形成json格式。无论数据多少在python中转不出来。【操作步骤&问题现象】1、按实验手册上的方法pd.read_json,显示“ValueError: Expected object or value”错误2、采用json.loads方式,显示“JSONDecodeError: Expecting value: line 2 column 1 (char 1)”错误但数据格式在https://www.json.cn/验证是对的(见截图),并能打印出,看来不是生成数据的问题。但就是从json中转不出。上网搜了很多方法,都试过(例如一行一行读、增加 strict=False参数、以及'r', encoding="utf-8-sig"参数),但都不行。3、采用 jsonlines也不行。请老师指点,谢谢!【截图信息】1、实验手册方法:2、其他方法:3、json数据验证:【日志信息】(可选,上传日志内容或者附件)
推荐直播
-
通用人工智能(AGI)到来前夕如何实现企业降本增效和应用现代化
2024/04/19 周五 14:00-16:00
李京峰 T3出行VP/CTO
李京峰是T3出行CTO,本次他将分享通用人工智能(AGI)到来前夕,如何实现企业降本增效和应用现代化。
回顾中 -
华为云云原生FinOps解决方案,为您释放云原生最大价值
2024/04/24 周三 16:30-18:00
Roc 华为云云原生DTSE技术布道师
还在对CCE集群成本评估感到束手无策?还在担心不合理的K8s集群资源申请和过度浪费?华为云容器服务CCE全新上线云原生FinOps中心,为用户提供多维度集群成本可视化,结合智能规格推荐、混部、超卖等成本优化手段,助力客户降本增效,释放云原生最大价值。
去报名 -
产教融合专家大讲堂·第①期《高校人才培养创新模式经验分享》
2024/04/25 周四 16:00-18:00
于晓东 上海杉达学院信息科学与技术学院副院长;崔宝才 天津电子信息职业技术学院电子与通信技术系主任
本期直播将与您一起探讨高校人才培养创新模式经验。
去报名
热门标签