Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

key - Accessing a single property in a JSON object

I am trying to access "token" inside of "tokens" array and set that token as the {{authToken}}. in Postman but I am having trouble with the proper syntax.

I tried this

if (pm.response.code === 201) {
    pm.environment.set('authToken', pm.response.json().tokens["token"])
}
{
 "idVerified": false,
    "idZip": 0,
    "subscription": 0,
    "emailVerified": false,
    "_id": "600f3cca17d9e88b126872cc",
    "username": "authtestx",
    "name": "JOHN",
    "email": "[email protected]",
    "tokens": [
        {
            "_id": "600f3cca17d9e88b126872cd",
            "token":    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MDBmM2NjYTE3ZDllODhiMTI2ODcyY2MiLCJpYXQiOjE2MTE2MTEzMzgsImV4cCI6MTYxMjA0MzMzOH0.2gChzDVG-IvxlHE8JSm0p9MkQHBmzePy70UqewbUNQ0"
        }
    ]
}
question from:https://stackoverflow.com/questions/65892972/accessing-a-single-property-in-a-json-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ur really close, since tokens is an array accessing the first element like this might do it

if (pm.response.code === 201){
pm.environment.set('authToken', pm.response.json().tokens[0].token)
}

i have tried it here, have a look : https://www.w3schools.com/code/tryit.asp?filename=GN2I6QBQYVFO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...