How to interpret javascript within a json file - javascript

I'm working with the form builder Alpaca, and I would like to interpret a javascript function within a json datasource file, to select a certain file :
/data/options.json :
"nature":{
"type": "select",
"dataSource": "function(e) {...}"
},
This file is loaded here :
/test.html :
$("#div").alpaca({
"optionsSource": "/data/options.json",
etc...
Is this possible ?
Thanks.

You can use eval as said :
object = {"nature":{
"type": "select",
"dataSource": "function(e) {alert('ok')}"
}
}
var x = eval("("+object.nature.dataSource+")");
x()
Demo

You could make the function call first, then add the result to you JSON with data.nature.push();
See this answer : Add data to JSON in JS
script type="text/javascript">
var JSON = {"nature":{
"type": "select"
}};
JSON.dataSource.push(function());
$("#form1").alpaca(JSON);
</script>

As the Alpace datasources doc, http://www.alpacajs.org/docs/api/datasources.html you can use custom function in the datasource parameter :
$("#field5").alpaca({
"schema": {
"type": "string",
"title": "Pick an Action Hero"
},
"options": {
"type": "select",
"dataSource": function(callback) {
callback([{
"value": "rambo",
"text": "John Rambo"
}, {
"value": "norris",
"text": "Chuck Norris"
}, {
"value": "arnold",
"text": "Arnold Schwarzenegger"
}]);
}
}
});

Related

ChaiJS jsonSchema check for multiple types

In my Chai-Test (using it for PostMan) I want to validate my API-response-design. For that I have written a Chai-Test:
pm.test("Check response schema", () => {
const schema = {
"type": "object",
"properties": {
"success": { "type": "boolean" },
"data": { "type": "object" },
"err": { "type": "object" },
"info": { "type": "string" }
},
"required": ["success", "data", "err", "info"]
}
pm.response.to.have.jsonSchema(schema)
})
My problem now is, that either the data or the err object is defined based on whether the request to the API was successful or not. I wanted to accomplish that by using two types for the data and the err: object AND null. So, how can I check for two types with the jsonSchema? Or is there an other and better way to do this?
You can do that:
"data": { "type": ["object", "null"] },
"err": { "type": ["object", "null"] }

Merge a Product Config JSON with Generic Config JSON- Issue While Merging Arrays inside it

I have 2 different Json files
1: a Deaflut JSON file
2: A Product Based JSON file
I need to merge them together in such a way that if a feature in default is not in a product that needs to be added to product config from default one.
for this merge, I used "lodash.mergewith" https://www.npmjs.com/package/lodash.mergewith.
so this is now taking care of the merge, But the file contains multiple nested JSON arrays inside it.
to handle that there is an option to use a customizer method that can handle array merge as mentioned in the usage of lodash.mergewith. I need a customizer that can find the Label from Deaflut and compare it with the Product if the Product has the same Label value then replace the URL with the Product URL. else if the Label is not in Product config, then use it from default as it is.
Example
Default config.json:-links is an array of this json with path : object►login►options►sections►2►links
"links": [{
"url": "www.google.com",
"label": "Lable1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
Productconfig.json:- links is an array inside this of the path: object►login►options►sections►2►links
"links": [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
]
** after merge mergedconfig.json "Links" need to be like this.**
"links": [{
"url": "www.product1.com",
"label": "Label1"
},
{
"url": "www.product2.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
The main concern is this Array is coming inside a JSON file inside some JSON objects
like eg if the Array is inside links[] it will be in a path like : object►login►options►sections►2►links[]. and this Links Array similarly present inside in some other paths eg: object►register►options►sections►2►links[]
So I need to figure out all the Array like this and for each of the Arrays, I need to perform this action.
Just use Array.map and Array.find:
let links= [
{
"url": "www.google.com",
"label": "Label1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
];
let plinks= [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
];
let results = links.map(lnk=>{
plnk = plinks.find(pl=>pl.label.toLowerCase()===lnk.label.toLowerCase());
return plnk || lnk
});
console.log(results);
for clean access to nested JSON keys you can use ES like this:
let a = {
b: {
c: [1,2,3]
}
};
let {c} = a?.b;
console.log(c);

Extract information from json

So I have the following object from my controller, which has a name, a list of beans and a list of operations:
{
"name": "Charge",
"beans": [
],
"operations": [
{
"name": "getSize",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
]
},
{
"name": "truncate",
"returnType": "java.lang.Void",
"description": "empty description",
"parameters": [
]
},
{
"name": "count",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "update",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaSelectCode",
"type": "java.lang.String",
"value": null
},
{
"name": "javaUpdateCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "delete",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "dump",
"returnType": "java.lang.Void",
"description": "empty description",
"parameters": [
{
"name": "javaSelectCode",
"type": "java.lang.String",
"value": null
},
{
"name": "destinationPath",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "select",
"returnType": "java.lang.String",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
}
],
"$$hashKey": "object:620"
}
Basically I want to display all the operations from this object in a dropdown menu.
So I was thinking of having something like:
<div ng-repeat="operation in object.operations">
{{operation.name}}
</div>
Except the code above doesn't display anything on the screen, no errors in the console, nothing.
Any help would be much appreciated!
EDIT:
Javascript service:
app.controller('selectAll', ['$http', '$scope' , '$rootScope', function ($http, $scope, $rootScope) {
$scope.response;
$scope.operations;
$rootScope.$on("invokeSelectAll", function(){
$scope.invokeSelectAll();
});
$scope.invokeSelectAll = function(){
$scope.response = $http.post('/invoke/selectAll/', $rootScope.dataObj);
$scope.object = JSON.stringify($rootScope.object);
console.log(" object operation from selectAll " + $scope.object);
$scope.response.then(function(data) {
$scope.responses = data.data ? data.data : "Select Operation not supported on this bean";
});
}
}]);
Screenshot of dev console:
https://imgur.com/a/8WAAL
Use JSON.stringify() to create a JSON string from a JavaScript object.
Use JSON.parse() to parse a JSON string to a JavaScript object.
In your case, you need to use JSON.parse() because you get a JSON string from the server and want to parse it to a JavaScript object.
$scope.object = JSON.parse($rootScope.object);
you are using JSON.stringify which is used to change javascript object to string and store it as a string only.
You should Parse the data with JSON.parse(), and the data becomes a JavaScript object. and you can easily use that in ng-repeat.
Try it ,It will work fine

How to create a global variable in WSO2 ESB - must be updatable

I've written an ESB resource which takes in a list of test cases, like the example below:
{
"tests": [
{ "type": "DSS", "url": "http://localhost:8280/testsuite/general/test" },
{ "type": "ESB", "url": "http://localhost:8280/testsuite/general/test" },
{ "type": "GREG", "url": "http://localhost:8280/testsuite/general/test" },
{ "type": "GW", "url": "http://localhost:8280/testsuite/general/test" },
{ "type": "MB", "url": "http://localhost:8280/testsuite/general/test" },
{ "type": "ID", "url": "http://localhost:8280/testsuite/general/test" },
{ "type": "BOGUS", "url": "http://localhost:8280/testsuite/general/test" }
]
}
The resource takes this in as a JSON array and loops through the elements using the XPATH expression //tests/type and generates a status message (200 if it can do anything, ERR if not).
Ideally, I'd like to be able to incrementally add the types into some sort of a global array property which would eventually become [DSS, ESB, GREG, GW, MB, ID, BOGUS] so I can write a script to run through this and produce a payload to return something like the below:
{
"results": [
{ "TYPE": "DSS", "STATUS": "200" },
{ "TYPE": "ESB", "STATUS": "200" },
{ "TYPE": "GREG", "STATUS": "200" },
{ "TYPE": "GW", "STATUS": "200" },
{ "TYPE": "MB", "STATUS": "200" },
{ "TYPE": "ID", "STATUS": "200" },
{ "TYPE": "BOGUS", "STATUS": "ERR" }
]
}
I've been searching for a way to do this for a couple of days now, to no avail so if it's simply not possible or if I've just been looking for the wrong thing, I don't know but I'd really like to avoid producing a static resource, enabling future expansion with minimal involvement for me.
You can save your payload in the gov registry with this script :
<script language="js"><![CDATA[
importPackage(Packages.org.apache.synapse.config);
mc.getConfiguration().getRegistry().newResource("gov:/trunk/Test/TestTypes",false);
mc.getConfiguration().getRegistry().updateResource("gov:/trunk/Test/TestTypes",mc.getPayloadXML().toString());
]]></script>
newResource create the resource if it does not exist
you can use
mc.getPayloadJSON() instead of mc.getPayloadXML()
A sample with a resource 'TESTSOF' like this :
<root>
<value><child>1</child></value>
<value><child>2</child></value>
<value><child>3</child></value>
</root>
You can iter all "value" with :
<property name="TESTSOF" expression="get-property('registry','gov:/trunk/TESTSOF')" type="OM"/>
<iterate continueParent="true" sequential="false" preservePayload="false" expression="$ctx:TESTSOF//value">
<target>
<sequence>
<log level="full"/>
</sequence>
</target>
</iterate>
A sample with JSON :
Load JSON as the current message :
<payloadFactory media-type="json">
<format>$1</format>
<args>
<arg evaluator="xml" expression="get-property('registry','gov:/trunk/Test/TestTypes')"/>
</args>
</payloadFactory>
Iterate :
<iterate continueParent="true" sequential="false" preservePayload="false" expression="//tests">
<target>
<sequence>
<log level="full"/>
</sequence>
</target>
</iterate>

parse facebook json javascript

I am using javascript api to get facebook comments.
i am getting the following json result , but how can i parse them to use on my page ?
{
"id": "1234567891_2823098717038_3160191",
"from": {
"name": "User",
"id": "1234567891"
},
"message": "comment only...",
"can_remove": true,
"created_time": "2012-05-05T07:43:11+0000"
},
{
"id": "1234567891_2823098717038_3160281",
"from": {
"name": "User",
"id": "1234567891"
},
"message": "just another comment...",
"can_remove": true,
"created_time": "2012-05-05T08:14:17+0000"
},
{
"id": "1234567891_2823098717038_3160336",
"from": {
"name": "user2",
"id": "56265654845454"
},
"message": "congratz dear :)",
"can_remove": true,
"created_time": "2012-05-05T08:29:05+0000"
}
],
"paging": {
"next": "http://link.dddd"
}
}
How can i loop through this and display the contents ?
jQuery solution is acceptable.
Thank you.
Use JQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/
assoc_data = jQuery.param(response); //where response is your json
$.ajax({
type: "POST",
url: "submit_fb_data.php",
data: assoc_data,
success: function(data) {
//etc
}
});
make sure you use a >=1.4 jquery version

Categories