Extract nested JSON array response object using JS Lodash in Postman - json

I want to learn how to use Lodash to extract variables from a JSON response because the traditional methods explained on other Postman questions do not explain an easy way to do this as I used to do it with json path in Jmeter.
I need to translate the following json paths to a Lodash expression that returns the same values as this JSON paths
1. FlightSegmentsItinerary[*].Flights[*].Key
2. $..Flights[*].Key
3. Travelers[*].[?(#.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")
JSON Response:
{
"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"
}
]
}
]
}
So far I was able to extract the travelers Keys (Travelers[*].Key) using this:
var jsonData = pm.response.json();
var travelerKeys = _.map(jsonData.Travelers, 'Key');
console.log("travelerKeys: " + travelerKeys);
Output: travelerKeys: 1.1,2.2
As you can see, the JSON path:
Travelers[*].Key
Looks like this in Lodash:
var travelerKeys = _.map(jsonData.Travelers, 'Key');
for this case.

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>
Another option might be to try JavaScript libraries such as 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>
Because Postman doesn't support fetch and XMLHttpRequest, the jsonpath.min.js file contents can be saved in environment variable, and then eval(pm.environment.get('jsonpath')); before use as described in
https://community.getpostman.com/t/adding-external-libraries-to-postman/1971/4

You have to tell Postman which Sandbox module you going to use using require function(refer below code). The error you get has some issue with Postman few of them works few of them not Here they are talking
and Here is the postman issue tracker
the code I tried and worked for me as
const moment = require('lodash');
var keys = _.chain(obj.Travelers)
.map("Key")
.flatten()
.unique()
.value();
console.log(keys);
output
Array:[]
0 : "1.1"
1 : "2.2"
form more details you can look at
Postman Sandbox API reference
postman-and-lodash-the-perfect-partnership

Related

react native json image

I want to print out JSON images as a variable.
This is my local JSON file (JsonData.json):
{
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": [ "1", "2" ],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2",
"name": "soup",
"condition": [ "2", "3" ],
"image": "./appetizer/soup.png"
},
…
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": [ "1" ],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": [ "2", "3" ],
"image": "./main/fish.png"
},
…
]
}
I filtered the name when condition="2". (salad,soup,fish)
This is the code for filtering name:
const newArray1 = [...JsonData["apptizer"], ...JsonData["main"]];
const JsonResult = newArray1.filter(item => {
if(item.condition.indexOf("2") !== -1) return item.name;
});
AND I want to get the image when condition="2".
How can I get them? And How can I print out them?
Do I have to use base64? If so, Can you tell me how to use it?
I saw the explanation, but I can't understand it.
And I imported JSON file this way (I've been correctly using it):
var JsonData = require('./JsonData.json');
You can use below code:
let mainObject = JSON.parse(JSON.stringify(data))
let allKeys = Object.keys(mainObject)
let finalObject = []
allKeys.map((value, index) => {
let array = mainObject[value]
array.map((aryObject, aryIndex) => {
let condition = aryObject['condition']
if (condition.includes('2')) {
finalObject.push(aryObject)
}
})
})
alert(JSON.stringify(finalObject))
You can import data in top of screen:
import { data } from './data';
You can add below text in data.js:
export const data = {
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": ["1"],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2222",
"name": "soup",
"condition": ["2", "3"],
"image": "./appetizer/soup.png"
},
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": ["1"],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": ["21", "3"],
"image": "./main/fish.png"
},
]
}
You can use Object#values to get the arrays corresponding to appetizer and main and then Array#flat to extract the nested objects into a transformed array. Then use the Array#filter (which you are already using) to filter out only the required objects based on your condition and then Array#map to get the name and image values out of every filtered object into an array of objects.
Please consider following snippts
const jsonData = {"appetizer":[{"num":"appetizer1","name":"salad","condition":["1","2"],"image":"./appetizer/salad.png"},{"num":"appetizer2","name":"soup","condition":["2","3"],"image":"./appetizer/soup.png"}],"main":[{"num":"main1","name":"beef","condition":["1"],"image":"./main/beef.png"},{"num":"main2","name":"fish","condition":["2","3"],"image":"./main/fish.png"}]};
const filteredValues = Object.values(jsonData)
.flat()
.filter(o => o.condition.includes('2'))
.map(({name, image}) => ({ name, image }));
console.log(filteredValues);
The output of the above code will be an array of objects having the following structure
[{
"name": SOME_NAME,
"image": SOME_PATH
},
{
"name": SOME_NAME,
"image": SOME_PATH
},
...
]
You can use the above array to retrieve your image path and display it accordingly.
I think you shouldn't be worried about base64 as images are stored locally and path will be sufficient to display the image.
Hope this will help!!!
Side Note: You can avoid the Array#flat part as you are already doing it manually [...JsonData["apptizer"], ...JsonData["main"]] but flat will be handy in case there are more keys in jsonData that need to be considered.

How to bind local JSON Model to MultiComboBox in SAPUI5?

how can I bind my local JSON model to my MultiComboBox.
The XML code for the combobox is looking as followed:
<MultiComboBox id="multiBox" selectionFinish="onBoxFinish"/>
The model looks like this:
var exampleData = {
"data": [{
"name": "Example1",
"value": "16.505406"
},
{
"name": "Example2",
"value": "6.65465"
},
{
"name": "Example3",
"value": "89.56456"
}]
};
I want to display the 3 names in the ComboBox.
Can someone help me with this?
Thanks.
Firstly, instantiate a JSONModel with your data. Secondly, set the JSONModel to your view. Thirdly, bind the model to your MultiComboBox.
var oData = {
"data": [
{
"name": "Example1",
"value": "16.505406"
},
{
"name": "Example2",
"value": "6.65465"
},
{
"name": "Example3",
"value": "89.56456"
}
]
};
var oModel = new JSONModel(oData);
this.getView().setModel(oModel);
<MultiComboBox
selectionFinish="onBoxFinish"
items="{/data}">
<core:Item
key="{name}"
text="{value}">
</core:Item>
</MultiComboBox>

Nested JSON Schema Validation in Postman

I want to validate a Nested JSON Schema in Postman.
Here is the code.
const testSchema = {
"name": [
{
"first_name": "Alpha",
"last_name": "Bravo"
},
{
"first_name": "Charlie",
"last_name": "Delta"
},
],
"age": "23",
"color": "black"
};
const showData = {
"required": ["name", "age"],
"properties": {
"name": [
{
"required": ["first_name"]
}
],
},
};
pm.test("Nested Schema Test", function () {
pm.expect(tv4.validate(testSchema, showData)).to.be.true;
});
Currently, this code returns test as true.
I am unable to test the "name" array objects' keys.
Even upon passing this:
"required": ["fst_nae"] //wrong key name
it returns true.
I would just check in easy way via:
pm.test("your name", function () {
pm.expect(testSchema.name[0].first_name && testSchema.name[1].first_name
).to.eql('Alpha' && 'Charlie')
});
and you successfully validated these fields
or use this expect to organize your code of your choice
tiny validator i.e. tv4.validate is having issues in their library. Another option is to use AJV (you can search it on github).

XML response to an express API

I have a node js program, which uses the express framework. What happens, is a POST request is made using Postman to my API, and I deal with the request as required (which works great).
However, I want send back an XML response to the API call. So doing some digging online, I have found this library - https://www.npmjs.com/package/xml
I tried to adapt it to my code, so I need to convert the following json object into an XML response:
var responseJson = [{
"methodResponse": {
"params": {
"param": {
"value": {
"struct": {
"member": [
{
"name": "myValue",
"value": {
"string": "hi"
}
}
]
}
}
}
}
}
}];
And then in the response I do the following:
res.header('Content-Type', 'text/xml');
res.send(xml(responseXml, true));
However this only returns:
<methodResponse/>
and nothing else in the Postman response.
Any idea what happened to the rest and why only one line is returned? Is there a better way to do this? Thanks
You need to put square brackets around your objects.
const data = [{
"methodResponse": [{
"params": [{
"param": [{
"value": [{
"struct": [{
"member": [{
"name": "myValue",
},{
"value": [{
"string": "hi"
}]
}]
}]
}]
}]
}]
}]
}];
Which will produce:
<methodResponse><params><param><value><struct><member><name>myValue</name><value><string>hi</string></value></member></struct></value></param></params></methodResponse>

evaluating json object returned from controller and attaching it to prepopulate attribute of tokeninput

I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}