0

I would like to read property names from response json and compare. example my json is line below,

var response = 
{
  "data": [
    {
      "name": "tester",
      "id": "123"
    }
  ],
  "includes": [
    {
      "name": "test",
      "id": "345"
    }
  ]
}

I want to check response.data[0] has the properties name and id. For this I tried to read property name like below,

var first = response.data[0];
var firstProperty = first[0]; //I expected like it will return [ "name"]. but its returning as undefined.

Note - to make it clear, I want to read the property name from json [name, id]. not the property value [tester, 123]

could someone help me please?

1
  • Well, the name field would be either response.data[0].name or response.includes[0].name
    – Taplar
    Commented Jul 3, 2020 at 17:06

2 Answers 2

1

What you're looking for is object.keys().

var first = response.data[0];
var firstProperty = Object.keys(object)[0]

Object.keys(myObj) returns an array with the keys. You can subset the first index, ie. "name" from this array.

Read more here => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

2
  • string first=response.data; foreach (var row in first) { Console.WriteLine(row.name); Console.WriteLine(row.id); } Commented Jul 3, 2020 at 17:19
  • You can display name,id as mentioned above Commented Jul 3, 2020 at 17:20
0

If your intention is to create a test to check the keys, you could create one and include an assertion like this:

pm.expect(response.data[0]).to.include.all.keys('name', 'id');

Not the answer you're looking for? Browse other questions tagged or ask your own question.