Concatenate value from the same JSON - json

I'm working on a configuration service in Angular 2 which simply retrieve the content of my JSON file defined above.
{
"application": {
"baseUrl": "http://localhost:1691/",
"environment": "dev"
},
"error": {
"title": "Title Error",
"description": "Error message"
}
}
I would like now, to add a properties using the baseUrl and concatenate a string after, I tried with this but it's obviously not working:
"baseApiUrl": baseUrl + "api/",
Is my requirement possible to do or have I to do it manually in my code?
My dream result would be something like this:
{
"application": {
"baseUrl": "http://localhost:1691/",
"baseApiUrl": baseUrl + "api/",
"environment": "dev"
},
"error": {
"title": "Title Error",
"description": "Error message"
}
}

My dream result would be something like this
JSON has no mechanism for referring to other parts of the structure like that. JSON is a very simple data-only format defined here.
Assuming you have that JSON as a string, you parse it, then add a property to the application object:
var configuration = JSON.parse(configurationString);
configuration.application.baseApiUrl = configuration.application.baseUrl + "api/";
Then depending on what you need to do with it, you either use configuration (the object), or turn it back into a string via JSON.stringify, or whatever else you need to do.

Related

ADF pipeline get dynamic count of input parameters

I have a pipeline where I want to pass a JSON to from 3rd party application.
simple JSON Example, but the keys could be different for each call
{
"name": "Here is a name",
"guaid": "123456-123456-123456-111112",
"owner": "my.email#example.com",
"description": "here comes my description"
}
Passing the JSON is not the problem but I do not want to configure each parameter in the JSON as an pipeline parameter inside my ADF because it is not needed.
I do not modify the JSON inside my pipeline, I just have to surround it with some other parameters, so I need it as a whole.
I cloud of course define a parameter for each key in the JSON and concatenate it again but why do the effort if it is not needed.
I also can not modify how the JSON will be passed to my pipeline, so it is not possible to pass the whole JSON inside one parameter like this:
{
"inputParam": "{\"name\": \"Here is a name\",\"guaid\": \"123456-123456-123456-111112\",\"owner\": \"my.email#example.com\",\"description\":\"here comes my description\"}"
}
so is it possible to get all input without "knowing" it and use it in my activity?
My Pipeline is just simple, I only need a set variable and web activities, so I want to avoid a complex solution.
JSON Outbutt should look like this
{
"processingMode": "full",
"version": "1.0.0",
"content": [
{
"type": "Application",
"id": "akjhajf-ffsfsfs-sf-sf-sf",
"data": {
"name": "Here is a name",
"guaid": "123456-123456-123456-111112",
"owner": "my.email#example.com",
"description": "here comes my description"
}
}
]
}
I achieve this by adding this in a set variable like this with the not allowed method i mentioned above
{
"processingMode": "full",
"version": "1.0.0",
"content": [
{
"type": "Application",
"id": "#{guid()}",
"data": #{pipeline().parameters.inputParam}
}
]
}
I then just use this result JSON and call a external Webservice via Web activity

POSTMAN How to parse a nested json object in postman which has dynamic keys?

supposing the json body returned from a call contains some dynamic keys ie
{
"message": "search results matching criteria",
"permission": {
"261ef70e-0a95-4967-b078-81e657e32699": {
"device": {
"read:own": [
"*"
]
},
"account": {
"read:own": [
"*"
]
},
"user": {
"read:own": [
"*"
]
}
}
}
I can validate the json as follows easily enough although I am having a lot of trouble working out how to validate the objects BELOW the dynamic guid level of the response.
pm.test("response body to have correct items", function () {
pm.expect(jsonData.message).to.eq("search results matching criteria");
pm.expect(jsonData).to.have.property('permission');
pm.expect(jsonData.permission).to.have.property(pm.variables.get("otherUserId"));
});
Would ideally like to verify the device and account and user levels of the object.
Anyone with some tips?
I've tried a few ways to try and reference the otherUserId variable but nothing is working. It is either not resolving the variable therefore failing the test as its looking for a level in the json called otherUserId or it fails to run the test due to a syntax error.
This works:
pm.expect(jsonData.permission[pm.variables.get("otherUserId")]).to.have.property('device');

Parse Dynamic Property name in Azure Logic App

I have been playing around with Azure Logic Apps and trying to retrieve a Pocket (ReadItLater) article so that I can create a new task in my preferred Task Manager. I have Two HTTP Connectors (one for Retrieve Operation using Pocket API and another post data to Todoist (my preferred task manager).
I can retrieve the Article and the response looks like (removed a few properties below for easy reading):
{
"statusCode": 200,
"headers": {
"pragma": "no-cache",
"status": "200 OK"
},
"body": {
"status": 1,
"complete": 1,
"list": {
"586327616": {
"item_id": "586327616",
"resolved_id": "586327616",
"given_url": "http://kenwheeler.github.io/slick/?utm_source=hackernewsletter&utm_medium=email&utm_term=design&mc_cid=58c9499fa2&mc_eid=3aaf6c4e47",
"given_title": "slick - the last carousel you'll ever need",
"time_added": "1396652224",
"time_updated": "1405156517",
"resolved_title": "slick",
"resolved_url": "http://kenwheeler.github.io/slick/?utm_source=hackernewsletter&utm_medium=email&utm_term=design&mc_cid=58c9499fa2&mc_eid=3aaf6c4e47",
"excerpt": "Add slick.js before your closing <body> tag, after jQuery (requires jQuery 1.7 +) <script type=\"text/javascript\" src=\"slick/slick.min.",
"word_count": "22"
}
}
}
}
Now I want to parse the above response to retrieve individual article properties (i.e. resolved_title). The issue here is the object under the list "586327616" is dynamic and changes for every article, and I can't seem to parse this as an expression in Logic App. My current action in Logic App looks like:
"postToTodoist": {
"conditions": [
{
"expression": "#equals(outputs('getPocketArticles')['statusCode'], 200)"
},
{
"dependsOn": "getPocketArticles"
}
],
"inputs": {
"body": "#{outputs('getPocketArticles')['body']['list'][0]['resolved_title']}",
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"method": "POST",
"repeat": {},
"uri": "https://todoist.com/API/v6/add_item"
},
"type": "Http"
}
For the expression I have tried converting the response to string, using coalesce and trying to access using an index, but nothing seem to work. In the error, it tells me what that the available property is i.e.:
{"code":"InvalidTemplate","message":"Unable to process template language expressions in action 'postToTodoist' inputs at line '1' and column '11': 'The template language expression 'coalesce(body('getPocketArticles')['list']).resolved_title' cannot be evaluated because property 'resolved_title' doesn't exist, available properties are '586327616'. Please see https://aka.ms/logicexpressions for usage details.'."}
I feel that it is not possible to construct an expression without knowing the name of the property, has anyone done something similar?

Removing excess comma on JSON Object

Currently been working on eliminating the excess "," comma on the json object I have below.
{"rules": {
"1000": {
"action": "2",
"category": "skype",
"entity": "Private",
"id": "1000",
},
"1200": {
"action": "2",
"category": "http",
"entity": "Public",
"id": "1200",
},
"100": {
"action": "2",
"category": "ftp",
"entity": "Public",
"id": "100",
},
"0": {
"entity": "Private",
"category": "alcohol, tobacco",
"action": "1",
"id": "low",
},
"3000": {
} }}
Maybe you have some insights on what's the cleanest way to eliminate it using AngularJS.
The data was parsed from this code snippet.
var request = {
url: 'sample/uri',
method: "GET",
transformResponse: specialTransform
};
var response = $q.defer( );
$http( request ).success( function( THIS DATA -> data, status ) {
eval
var fixTrailingCommas = function (jsonString) {
var jsonObj;
eval('jsonObj = ' + jsonString);
return JSON.stringify(jsonObj);
};
fixTrailingCommas('{"rules": { "1000": { "action": "2", "category": "skype", "entity": "Private", "id": "1000" , } } }');
Please use eval here only if you completely trust incoming json, and also be aware of other eval evils as described on MDN and its note on JSON parsing
Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.
You may also choose to rely on implementation of JSON2 by Douglas Crockford which uses eval internally
On current browsers, this file does nothing,
preferring the built-in JSON object. There is no reason to use this file unless
fate compels you to support IE8, which is something that no one should ever
have to do again.
But because we really need to use this library, we have to make few code modifications, e.g. simply comment out JSON type check, which will then override native browser object (or we may also introduce new JSON2 global variable)
//if (typeof JSON !== 'object') {
JSON = {};
//}
P.S. Other parsing fuctions json_parse.js and json_parse_state.js, which don't use eval, throw a syntax error
Angular part
var config = {
transformResponse: function (data, headers) {
if(headers("content-type") === "application/json" && angular.isString(data)) {
try {
data = JSON.parse(data);
} catch (e) {
// if parsing error, try another parser
// or just fix commas, if you know for sure that the problem is in commas
data = JSON2.parse(data);
}
return data;
} else {
return data;
}
}
};
$http.get("rules.json", config).success(function (data) {
$scope.rules = data;
});
So as you said, the JSON is wrongly generated on the server you are taking it from, can you change the way it is generated there? (Follow this: Can you use a trailing comma in a JSON object?)
In case you are unable to do so, you need to use something like mentioned here:
Can json.loads ignore trailing commas?
library to repair a JSON object, like: https://www.npmjs.com/package/jsonrepair
(try some online fix tool here: http://www.javascriptformat.com/)
or some regexp magic

apigee - Json payload extract variables

I am confused why the extractVariables rule I am using is returning data as it is. See Below.
The json to Parse is:
{
"callNotificationSubscriptionList": {
"playAndCollectInteractionSubscription": [],
"recognitionInteractionSubscription": [],
"playAndRecordInteractionSubscription": [],
"callDirectionSubscription": [],
"callEventSubscription": [
{
"clientCorrelator": "112345",
"resourceURL": "http:someurl",
"callbackReference": {
"notifyURL": "someotherurlt",
"notificationFormat": "XML"
},
"filter": {
"data1": "data abc",
"data2": "data def",
"data3": "data xyz"
}
}
]
}
}
The rule:
<JSONPayload>
<Variable name="callNotSubL">
<!-- <JSONPath>$.callNotificationSubscriptionList</JSONPath> -->
<JSONPath>$.*</JSONPath>
</Variable>
</JSONpayload>
When I use the value that is commented out, I get no response variable data. If I set the "ignoreUnresolvedVariables" parm to "false", I am returned a failure, so it has no data. Thus, I tried "$.*" With this, I am returned:
[
{
"callbackReference": {
"notifyURL": "someotherurlt",
"notificationFormat": "XML"
},
"filter": {
"data1": "data abc",
"data2": "data def",
"data3": "data xyz"
}
}
]
could this be because the EntryNames are so long? I admit they are long, but they are well under the default values in the JSON Threat Potection Policy.
I did pump this json though a web based JSONPayload parser and $.callNotificationSubscriptionList worked fine as did $.callNotificationSubscriptionList.callEventSubscription[0] which is what I am really after. But, if I can't get the top level right, I can't get the sub-levels at all.
I solved this issue using #Santanu's comments:
It seems that the JSON to parse getting through the policy is not same as what you are expecting? Can you try to assign entire payload to a variable using the AssignVariable policy before the JSON path extraction policy, and check the value of that variable in the debug view? That would help understand what payload value is actually passing through when you are trying to apply the json path extraction policy.
the <Source> tag was "request" and this was a response extract. I removed the <Source> tag and all is well