如何在邮递员中从 JSONArray 获取 JSONobject [英] How to get JSONobject from JSONArray in postman

查看:19
本文介绍了如何在邮递员中从 JSONArray 获取 JSONobject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用测试脚本在邮递员中自动化注册场景我有以下 JsonArray 作为响应:

I am trying to automize a registration scenario in postman using test scripts I have the following JsonArray as a response:

[
    {
        "id": 1,
        "name": "user_A",
        "cntkp": "martin",
        "company": "kreativ",
        "tel": "12345678",
        "email": "user_A@gmail.com"
        "street": "str. 0001",
        "city": "DEF",
    }
    ......
    ......
    ......
    {
        "id": 4,
        "name": "user_B",
        "cntkp": "martin",
        "company": "kreativ",
        "tel": "12345678",
        "email": "user_B@gmail.com"
        "street": "str. 0002",
        "city": "NJ",
    }
    ......
    ......
    ......
    {
        "id": 10,
        "name": "User_C",
        "cntkp": "martin",
        "company": "kreativ",
        "tel": "12345678",
        "email": "user_C@gmail.com"
        "street": "str. 0003",
        "city": "ABC",
    }
    ......
]

数组长度可以是动态的和改变的(在这个示例中是 10),并且想要找到具有特殊电子邮件的对象(在数组中的某个位置),然后从该对象中获取 ID 并基于 JsonData 进行断言对象(捕获元素,例如检查名称).

the array length can be dynamic and changed (in this sample is 10) and want to find the object with special email (somewhere in the array) and then get the ID from that object and make the assertion based on JsonData from this object (catch elements e.g. check name).

我该怎么做?

感谢您的支持.

我发送一个 GET 请求以从注册数据库中获取所有数据.作为回应,我得到一个 JsonArray从 Json Array 我需要断言的特定对象(例如,示例中带有电子邮件 user_B 的对象).我知道我的电子邮件地址,并且基于它我必须从 Object 中找出 ID.当我知道哪个 ID 是我的 ID 时我可以这样做,但如果它是动态的,我不知道如何在邮递员中搜索数组以获取 ID

I send a GETrequest to get all Data from Registration DB. as response I get a JsonArray from Json Array I need the specific Object for the assertion (e.g. object with email user_B in sample) . I know my Email address and base on it I have to findout the ID from Object . I can do it when I know which ID is my ID but in case it is dynamic I don't know how to search an array for it in postman to get ID

例如,断言公司名称

pm.expect(jsonData[0].company).to.equal(pm.environment.get("regDB_new_company"))

但如果我不知道 ID(只知道我的电子邮件),我必须先找出 Object 的 ID,然后我才能断言它.

but if I dont know the ID ( only know my email) I have first to find out the ID of Object then I can asser it.

例如在这种情况下,首先找到带有电子邮件user_B@gmail.com"的对象然后从该对象获取 ID 元素(在本例中为 4)然后我想断言来自对象的所有数据

e.g. in this case first, find the object with email "user_B@gmail.com" then from that object get ID element (in this case 4) then I want to assert for all data from the object

推荐答案

谢谢 Danny,我找到了解决方案

Thanks Danny, I found the solution

var arr = pm.response.json()

for(i = 0; i < arr.length; i++) {
    if (arr[i].email == "userB@gmail.com") {
        pm.environment.set("personID", arr[i].id)
    }
}

这篇关于如何在邮递员中从 JSONArray 获取 JSONobject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆