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>
Related
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
I'm using Amazon MWS API. When using mock requests provided by the lib MerchantFulfillment, I see that the com.amazonservices.mws.client.MwsJsonBuilder returns an ISO8601 date not wrapped into a string. E.g.
{
"xmlns":"https:\/\/mws.amazonservices.com\/MerchantFulfillment\/2015-06-01",
"CancelShipmentResult":{
"Shipment":{
"ShipmentId":"String",
"AmazonOrderId":"String",
"SellerOrderId":"String",
"ItemList":[
{
"OrderItemId":"String",
"Quantity":1
}
],
"ShipFromAddress":{
"Name":"String",
"AddressLine1":"String",
"AddressLine2":"String",
"AddressLine3":"String",
"DistrictOrCounty":"String",
"Email":"String",
"City":"String",
"StateOrProvinceCode":"String",
"PostalCode":"String",
"CountryCode":"String",
"Phone":"String"
},
"ShipToAddress":{
"Name":"String",
"AddressLine1":"String",
"AddressLine2":"String",
"AddressLine3":"String",
"DistrictOrCounty":"String",
"Email":"String",
"City":"String",
"StateOrProvinceCode":"String",
"PostalCode":"String",
"CountryCode":"String",
"Phone":"String"
},
"PackageDimensions":{
"Length":100,
"Width":100,
"Height":100,
"Unit":"String",
"PredefinedPackageDimensions":"String"
},
"Weight":{
"Value":100,
"Unit":"String"
},
"Insurance":{
"CurrencyCode":"String",
"Amount":100
},
"ShippingService":{
"ShippingServiceName":"String",
"CarrierName":"String",
"ShippingServiceId":"String",
"ShippingServiceOfferId":"String",
"ShipDate":1969-07-21T02:56:03Z,
"EarliestEstimatedDeliveryDate":1969-07-21T02:56:03Z,
"LatestEstimatedDeliveryDate":1969-07-21T02:56:03Z,
"Rate":{
"CurrencyCode":"String",
"Amount":100
},
"ShippingServiceOptions":{
"DeliveryExperience":"String",
"DeclaredValue":{
"CurrencyCode":"String",
"Amount":100
},
"CarrierWillPickUp":true,
"LabelFormat":"String"
},
"AvailableLabelFormats":[
"String"
]
},
"Label":{
"CustomTextForLabel":"String",
"Dimensions":{
"Length":100,
"Width":100,
"Unit":"String"
},
"FileContents":{
"Contents":"String",
"FileType":"String",
"Checksum":"String"
},
"LabelFormat":"String",
"StandardIdForLabel":"String"
},
"Status":"String",
"TrackingId":"String",
"CreatedDate":1969-07-21T02:56:03Z,
"LastUpdatedDate":1969-07-21T02:56:03Z
}
},
"ResponseMetadata":{
"RequestId":"String"
}
}
So, for instance, "EarliestEstimatedDeliveryDate":1969-07-21T02:56:03Z does not look like a valid JSON. Jackson's ObjectMapper fails, clearly, complaining about the hyphen.
Am I doing something wrong?
got this json file:
[
{
"name": "paprika",
"imgSrc": "img/paprika.jpg"
},
{
"name": "kurkku",
"imgSrc": "img/kurkku.jpg"
},
{
"name": "porkkana",
"imgSrc": "img/porkkana.jpg"
},
{
"name": "lehtisalaatti",
"imgSrc": "img/lehtisalaatti.jpg"
},
{
"name": "parsakaali",
"imgSrc": "img/parsakaali.jpg"
},
{
"name": "sipula",
"imgSrc": "img/sipuli.jpg"
},
{
"name": "peruna",
"imgSrc": "img/peruna.jpg"
},
{
"name": "soijapapu",
"imgSrc": "img/soijapapu.jpg"
},
{
"name": "pinaatti",
"imgSrc": "img/pinaatti.jpg"
}
]
Which I successfully fetch in a factory:
factory('getJson', ['$resource', function($resource) {
return $resource('json/vegs.json', {}, {
query: {method:'GET', isArray:true}
});
}]);
in my Controller I can get the json's file content:
var vegs = getJson.query();
$scope.vegs = vegs;
console.log(vegs)
console.log(typeof vegs)
The weird part is the first console.log produces an array of objects, as expected.
The second console says it's an "object", and not an array.
I can get the .json content to my view using {{vegs}}, and I can use ng-repeat as well, tho in the controller I can't do vegs[0] or vegs.length. It comes out empty.
I'm breaking my head on this for over 3 hours now :)
This isn't an 'answer'. Just an observation on one part of your issue. (Sorry, can't comment yet...new to stackoverflow).
Just a note on your comment that "The second console says it's an "object", and not an array." Using typeof on an array will always return "object".
There are various (and debated, it seems) ways to test if it's an array--Array.isArray(obj) for example.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
I want to parse this json object in javascript and have to obtain the values of key pass in string format.
{
"isSuccessful": true,
"resultSet": [
{
"name": "a",
"pass": "123",
"time_stamp": "2014-04-07T10:13:17.000Z"
},
{
"name": "chetan",
"pass": "123456",
"time_stamp": "2014-04-07T10:13:34.000Z"
},
{
"name": "dileep",
"pass": "456321",
"time_stamp": "2014-04-07T10:13:54.000Z"
},
{
"name": "bnc",
"pass": "654321",
"time_stamp": "2014-04-07T10:19:37.000Z"
}
]
}
If you are asking in a general sense (no links to Worklight) I would look at other answers:
How do I iterate over a JSON structure?
JavaScript loop through json array?
How do I loop through or enumerate a JavaScript object?
In Worklight, if your example is the response of a Worklight adapter, the response will be in a property called invocationResult.
See also https://www.ibm.com/developerworks/community/blogs/worklight/entry/handling_backend_responses_in_adapters?lang=en
I have been trying to access/parse the “message” object found in the JSON results hereafter, issued by the Facebook Graph API, using the Javascript JQuery $.each(function()) Function but without success. I am able to access the “name” object, but not the objects found in the statuses=>data array. I have tried a multitude of syntaxes, but without success. I was wondering if one could provide a syntactical example using the Javascript JQuery $.each(function()) Function of how I could access the “message” object. As you will notice, the “message” objects are found under the following structure: results=>friends=>data array=>statuses=>data array=>message.
{
"id": "idValue",
"friends": {
"data": [
{
"name": "NameValue",
"id": "idValue",
"statuses": {
"data": [
{
"message": "Msg1",
"updated_time": "Date",
},
{
"message": "Msg2",
"updated_time": "Date",
},
],
}
},
{
"name": "NameValue",
"id": "idValue",
"statuses": {
"data": [
{
"message": "Msg1",
"updated_time": "Date",
},
{
"message": "Msg2",
"updated_time": "Date",
},
],
}
}
],
}
}
Assuming that that block is stored in response:
console.log(response);
$.each(response.friends.data, function(i, friend){
console.log(friend);
$.each(friend.statuses, function(i, status){
console.log(status);
});
});
Un-tested, but it should work. It helps to console.log along the way to be sure what you're looking at. See the log in the inspector in Chrome or Firefox