0

I have an API which has response as below:

"message": "Success!",
    "user": {
        "id": 17,
        "first_name_kanji_or_hiragana": "Hiragana",
        "last_name_kanji_or_hiragana": "Name",
        "first_name_katakana": null,
        "last_name_katakana": null,
        "email": "user@example.com",
        "image_path": null,
        "email_verified_at": "2019-03-06 04:44:46",
        "type": "admin",
        "created_at": "2019-03-06 04:44:46",
        "updated_at": "2019-03-06 04:44:46",
        "deleted_at": null,
        "full_name": "Name Hiragana",
        "full_image_path": null,
        "roles": [

Each time when i am running the API new user id is generating. What i want to do is that i want to fetch the id each time i run the api & then want to use that id in next response. I have used below code to fetch the id but it's not working

pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody); 
jsonData.data.user[0].id
adiga
  • 34,372
  • 9
  • 61
  • 83
Sumaiya
  • 23
  • 2
  • 5
  • The above json doesn't seems to have array of user so your code should be 'jsonData.data.user.id' instead of 'jsonData.data.user[0].id' – Andrew Rayan Mar 06 '19 at 05:22

3 Answers3

0
pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody); 
jsonData.data.user[0].id // youre access the user if its array its not

Just use jsonData.data.user.id or jsonData.data.user[id]

Hamza Ahmed
  • 521
  • 5
  • 12
0

You are trying to access an array called user

jsonData.data.user[0].id

But user is an object, so you need to access: jsonData.data.user.id

There are sometimes that you need to check the complete json directly from your request.

Mauricio Toledo
  • 630
  • 7
  • 10
0

user is not an array. Try the below one.

jsonData.data.user.id

Your solution will work when you have the JSON like below,

    "lib_folders": {
        "changed": false,
        "examined": 5,
        "failed": false,
        "files": [
            {
                "atime": 1549608521.3831923,
                "ctime": 1548742613.5470872,
                "path": "/root/abc/xyz",
                "xusr": true
            },
            {
                "atime": 1549608521.4031928,
                "ctime": 1548742462.3279672,
                "path": "/root/123/456",
                "xusr": true
            }
        ],
        "matched": 2,
        "msg": ""
    }

For the above JSON if you want to get the path of the first file, then use the below code,

jsonData.data.lib_folders.files[0].path

Ameen Ali Shaikh
  • 409
  • 1
  • 3
  • 10