获取键:子块内的值对

时间:2019-11-18 10:53:44

标签: javascript json postman postman-pre-request-script

我有Postman的以下输出或达到终点(可以说)。

{
  "SearchResult": {
    "total": 11,
    "resources": [
      {
        "id": "12345",
        "name": "GuestType",
        "description": "Identity group ",
      },
      {
        "id": "56789",
        "name": "Admin",
        "description": "",
      },
    ]
  }
}

我想从这些值中提取"id""name"。我看到这些值在子块内。 如何使用需要放入邮递员“测试”标签中的Java脚本提取这些键值?

3 个答案:

答案 0 :(得分:1)

var obj={
  "SearchResult": {
    "total": 11,
    "resources": [
      {
        "id": "12345",
        "name": "GuestType",
        "description": "Identity group ",
      },
      {
        "id": "56789",
        "name": "Admin",
        "description": "",
      },
    ]
  }
}


obj.SearchResult.resources.forEach((o)=>console.log(o.id,o.name));

答案 1 :(得分:1)

下面的代码将仅返回具有ID和名称的对象数组。...快乐的编码:)

let data = {
  "SearchResult":
  {
    "total": 11,
    "resources": [
      { "id": "12345", "name": "GuestType", "description": "Identity group ", },
      { "id": "56789", "name": "Admin", "description": "", }
    ]
  }
}

let ids = data.SearchResult.resources.map(obj => {
  id: obj.id,
  name: obj.name
});

答案 2 :(得分:0)

尝试

let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);

let data={ "SearchResult": { "total": 11, "resources": [ { "id": "12345", "name": "GuestType", "description": "Identity group ", }, { "id": "56789", "name": "Admin", "description": "", }, ] } }

let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);

console.log(ids);
console.log(names);