【问题标题】:Extract nested JSON array response object using JS Lodash in Postman在 Postman 中使用 JS Lodash 提取嵌套的 JSON 数组响应对象
【发布时间】:2019-07-03 01:21:25
【问题描述】:

我想学习如何使用 Lodash 从 JSON 响应中提取变量,因为在其他 Postman 问题中解释的传统方法并没有像我以前在 Jmeter 中使用 json 路径那样解释一个简单的方法。

我需要将以下 json 路径转换为 ​​Lodash 表达式,该表达式返回与此 JSON 路径相同的值

1. FlightSegmentsItinerary[*].Flights[*].Key 
2. $..Flights[*].Key
3. Travelers[*].[?(@.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")

JSON 响应:

 {
"Travelers": [
    {
        "TypeCode": "ADT",
        "FirstName": "FULANO",
        "Surname": "LAZARO",
        "Key": "1.1"
    },
    {
        "TypeCode": "INF",
        "FirstName": "MENGANO",
        "Surname": "XULO",
        "Key": "2.2"
    }
],
"FlightSegmentsItinerary": [
    {
        "Flights": [
            {
                "Key": "1"
            },
            {
                "Key": "2"
            }
        ]
    }
]
}

到目前为止,我能够使用以下方法提取旅行者密钥 (Travelers[*].Key):

var jsonData = pm.response.json();    
var travelerKeys = _.map(jsonData.Travelers, 'Key');
console.log("travelerKeys: " + travelerKeys);
Output: travelerKeys: 1.1,2.2

如你所见,JSON 路径:

旅行者[*].Key

在 Lodash 中看起来像这样:

var travelerKeys = _.map(jsonData.Travelers, 'Key');

对于这种情况。

【问题讨论】:

  • 前 2 个 JSON 路径的结果有什么不同吗,所有 3 个 JSON 路径都会导致数组/多个项目吗?
  • 没有 xD,那两个返回相同,我只是想知道获得相同结果的不同方法。是的,它们都应该返回一个包含多个项目的数组

标签: json postman lodash


【解决方案1】:

var jsonData = {
  "Travelers": [{
      "TypeCode": "ADT",
      "FirstName": "FULANO",
      "Surname": "LAZARO",
      "Key": "1.1"
    },
    {
      "TypeCode": "INF",
      "FirstName": "MENGANO",
      "Surname": "XULO",
      "Key": "2.2"
    }
  ],
  "FlightSegmentsItinerary": [{
    "Flights": [{
        "Key": "1"
      },
      {
        "Key": "2"
      }
    ]
  }]
}

// 1. FlightSegmentsItinerary[*].Flights[*].Key 
console.log( _(jsonData.FlightSegmentsItinerary).flatMap('Flights').map('Key') ) 

//2. $..Flights[*].Key
console.log( _.chain(jsonData).values().flatten().find('Flights').values().flatten().map('Key') )

//3. Travelers[*].[?(@.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")
console.log( _(jsonData.Travelers).filter(['TypeCode', 'INF']).map('FirstName') )
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

另一种选择可能是尝试 JavaScript 库,例如 https://github.com/dchester/jsonpath

var jsonData = {
  "Travelers": [{
      "TypeCode": "ADT",
      "FirstName": "FULANO",
      "Surname": "LAZARO",
      "Key": "1.1"
    },
    {
      "TypeCode": "INF",
      "FirstName": "MENGANO",
      "Surname": "XULO",
      "Key": "2.2"
    }
  ],
  "FlightSegmentsItinerary": [{
    "Flights": [{
        "Key": "1"
      },
      {
        "Key": "2"
      }
    ]
  }]
}

console.log(jsonpath.query(jsonData, '$.FlightSegmentsItinerary[*].Flights[*].Key'))

console.log(jsonpath.query(jsonData, '$..Flights[*].Key'))

console.log(jsonpath.query(jsonData, '$.Travelers..[?(@.TypeCode == "INF")].FirstName')) 
<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.0.2/jsonpath.min.js"></script>

由于Postman不支持fetch和XMLHttpRequest,所以可以将jsonpath.min.js文件内容保存在环境变量中,然后eval(pm.environment.get('jsonpath'));在使用前按照描述 https://community.getpostman.com/t/adding-external-libraries-to-postman/1971/4

【讨论】:

  • 我正在尝试使用 Lodash,因为它带有 Postman。正如您所说,我在使用 Postman 时遇到问题,我收到错误消息:“TypeError | 无法读取未定义的属性 'flatMap'”。我将尝试解决此问题。
  • @Victor 问题不在于flatMap,而在于未找到之前的问题。如果jsonData.Travelers 有效,那么我看不出jsonData.FlightSegmentsItinerary 无效的原因.. 可能是拼写或大小写错误?
  • 我试过这些:console.log( obj.FlightSegmentsItinerary.flatten(o => o.Flights).map(o => o.Key) ); -> 返回空数组。然后我做了console.log( obj.FlightSegmentsItinerary_.flatMap(o => o.Flights).map(o => o.Key) );,它返回“TypeError |无法读取未定义的属性'flatMap'”。
  • 然后我做了 obj.FlightSegmentsItinerary.flatMap(o => o.Flights).map(o => o.Key) -> 返回 TypeError | obj.FlightSegmentsItinerary.flatMap 不是函数,最后是 obj.FlightSegmentsItinerary.flat(o => o.Flights).map(o => o.Key) - > TypeError | obj.FlightSegmentsItinerary.flat 不是函数”。我还添加了 var obj 进行测试,但是是的,我可以使用我已经拥有的 var jsonData。
  • @Victor 我添加了一个 jsonpath 示例,可能比学习 Lodash 容易一些
【解决方案2】:

您必须使用require 函数告诉 Postman 您要使用哪个沙盒模块(请参阅下面的代码)。你得到的错误与邮递员有一些问题,他们中的少数人不是Here they are talking 和Here is the postman issue tracker

我尝试并为我工作的代码

const moment = require('lodash');
var keys = _.chain(obj.Travelers)
        .map("Key")
        .flatten()
        .unique()
        .value();
console.log(keys);

输出

Array:[]
0 : "1.1"
1 : "2.2"

更多细节可以看
Postman Sandbox API reference
postman-and-lodash-the-perfect-partnership

【讨论】:

  • 我已经从只使用这个中得到了这个:var travelerKeys = _.map(jsonData.Travelers, 'Key');。因此这实际上并不能回答真正的问题,即 FlightSegmentsItinerary 中的键实际上比 Travelers 键更深。另外,我有这个: var _ = require('lodash');并且您的代码起初不起作用。然后我把它改成 const moment = require('lodash');它确实奏效了。不过,我喜欢这个答案,我需要研究它的属性,看看如何在 FlightSegmentsItinerary 中获取嵌套的 Key 数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多