jstree, json, ajax: Recursive Search and Select - javascript

I have jstree setup to load all content via ajax and json. Is it possible for the script to execute my ajax/json url and keep sub-searching when possible, if it finds it open all sub nodes until its visible and select it (.jstree-clicked). And is such a feature built in, if not know any where I could start with this? I am not the most fluent at javascript.
Here is my setup:
$("#jstFormMirror").jstree({
"types" : {
"types" : {
"default" : {
"select_node" : function(e) {
this.toggle_node(e);
return true;
}
}
}
},
"ui" : {
"select_limit" : 1,
"selected_parent_close" : "select_parent"
},
"json_data" : {
"progressive_unload" : true,
"ajax" : {
"url" : "/back-end/json/categories.json",
"data" : function (n) {
return { id : n.attr ? n.attr("id") : 0 };
}
}
},
"plugins" : [ "themes", "json_data", "types", "ui" ],
"core": {
"animation": 100
}
}).bind("select_node.jstree", function(event, data) {
$("#category").val($(".jstree-clicked").parent().attr("rel"));
})
And he is a typical json response when the script loads a node:
[
{
"attr": {
"id": "87"
},
"data": {
"title": "Bevel Clusters-Over 350 Designs",
"attr": {
"href": "#",
"rel": "658"
}
},
"state": "closed"
},
{
"attr": {
"id": "394"
},
"data": {
"title": "Bevels, Straight Lines-Over 210 Shapes & Sizes",
"attr": {
"href": "#",
"rel": "321"
}
},
"state": "closed"
}
]
I want to execute:
$("#jstFormCategories").jstree("search", ID_HERE);

For this, DefiantJS is excellent (http://defiantjs.com).
This lib extends the global object JSON with the method "search" and enables you to search a JSON structure with XPath expressions.
To understand how easy XPath (which is a standardised query language) is, check out this tool;
http://www.defiantjs.com/#xpath_evaluator
Here is a working fiddle;
http://jsfiddle.net/hbi99/vV43F/
var data = [
{
"attr": {
"id": "87"
},
"data": {
"title": "Bevel Clusters-Over 350 Designs",
"attr": {
"href": "#",
"rel": "658"
}
},
"state": "closed"
},
{
"attr": {
"id": "394"
},
"data": {
"title": "Bevels, Straight Lines-Over 210 Shapes & Sizes",
"attr": {
"href": "#",
"rel": "321"
}
},
"state": "closed"
}
],
res = JSON.search( data, '//*[id=394]/../data' );
console.log( res[0].title );

Related

Can elasticsearch with node, update only a certain field without rewrite?

My document has a field that looks like this:
_source:
...
"produto_tags" : [
{
"id_produto_cor" : "1623153806",
"tags" : []
},
{
"id_produto_cor" : "875623985732",
"tags": []
},
{...}
...
I need to insert on this field another Object without rewrite the entire produto_tags
data to be inserted:
{
"id_produto_cor" : "312411",
"tags": []
},
and my final document will looks like this:
_source:
...
"produto_tags" : [
{
"id_produto_cor" : "1623153806",
"tags" : []
},
{
"id_produto_cor" : "875623985732",
"tags": []
},
{
"id_produto_cor" : "312411",
"tags": []
}
]
Im using NODE js, I`m using this but it rewrites what I put :
const query = {
doc: {
nome_relatorio: nome_relatorio,
produto_tags: produto_tags,
referencia_tags: referencia_tags,
}
};
return await esClient.update({
index: indexName,
body: query,
id: id,
method: 'post',
type: typeDoc,
})
1. You can use update_by_query api
POST <index_name>/_update_by_query
{
"script": {
"source": "ctx._source.produto_tags.add(params.product)",
"params": {
"product": {
"product_id": "1004600287",
"tags": []
}
}
},
"query": {
"match_all": {} --> select the document
}
}
2. Update api
POST <index_name>/_update/<doc_id>
{
"script": {
"source": "ctx._source.produto_tags.add(params.product)",
"lang": "painless",
"params": {
"product": {
"product_id": "11",
"tags": []
}
}
}
}

Using anyOf to see objects name?

I have a schema here where I would like to have a drop down, to select an option, and from there - depending on the selection different options appear; all being nested within an array to have multiples of them.
I have noticed that when I am filling in with dummy data, the output json isnt storing the name of the selected option
so the data.json looks something like this:
{
"page1": [
{
"imageOptions": {
"imageHeightType": "vh",
"imageHeight": 50
},
"textboxArea": {
"headerText": "Header for selection1",
"headingTag": "h1",
"textBoxOpacity": 15
}
},
{
"content": "This is a complety different selection, yet there is no name to tell the difference between these two difference objects"
}
]
}
As you can see theres no object to wrap these two different items within the page1 array - Ideally would like something like:
{
"page1": [
{
// Title of object goes here from schema
"imageOptions": {
"imageHeightType": "vh",
"imageHeight": 50
},
"textboxArea": {
"headerText": "Header for selection1",
"headingTag": "h1",
"textBoxOpacity": 15
}
},
{
// Title of object goes here from schema
"content": "This is a completely different selection, yet there is no name to tell the difference between these two difference objects"
}
]
}
Is there a way to make this so? I have looked on the docs for AnyOf but not much luck. Quite new to React-JsonSchema-Forms.
Below is my current Schema:
{
"type": "object",
"properties": {
"page1": {
"type": "array",
"items": {
"type": "object",
"anyOf": [
{
"title": "Full Width Image",
"type": "object",
"properties": {
"imageOptions": {
"type": "object",
"title": "Image",
"properties": {
"image": {
"type": "string",
"title": "Image",
"format": "data-url"
},
"imageHeightType": {
"enum": [
"px",
"vh"
]
},
"imageHeight": {
"type": "number",
"title": "Image Height"
}
}
},
"textboxArea": {
"type": "object",
"title": "Textbox Area",
"properties": {
"headerText": {
"type": "string",
"title": "Heading Text"
},
"headingTag": {
"enum": [
"h1",
"h2",
"h3"
]
},
"imageText": {
"type": "string",
"title": "Body Text"
},
"textboxPosition": {
"title": "Textbox Position",
"enum": [
"Left",
"Center",
"Right"
]
},
"textboxColor": {
"title": "Color of Textbox Area",
"type": "string"
},
"textBoxOpacity": {
"title": "Textbox Opacity %",
"type": "integer",
"minimum": 0,
"maximum": 100,
"multipleOf": 5
}
}
}
}
},
{
"title": "Custom Block",
"type": "object",
"properties": {
"content": {
"type": "string"
}
}
}
]
}
}
}
}
Also Link to the online schema editor if it helps understand my issue
Why not just add a name-like property to each object? You can then hide/disable it if you want:
schema:
"anyOf": [
{
"title": "Full Width Image",
"type": "object",
"properties": {
"name": {
"type": "string",
"default": "fullWidthImage"
},
"imageOptions": {
"type": "object",
"title": "Image",
"properties": {...}
...
}
...
}
},
{
"title": "Custom Block",
"type": "object",
"properties": {
"name": {
"type": "string",
"default": "custom"
},
"content": {
"type": "string"
}
}
}
]
uiSchema:
{
"page1": {
"items": {
"name": {
"ui:widget": "hidden"
},
"imageOptions": {...},
...
}
}
formData then should look like this:
{
"page1": [
{
"name": "fullWidthImage",
"imageOptions": {
"imageHeightType": "vh",
"imageHeight": 50
},
"textboxArea": {
"headerText": "Header for selection1",
"headingTag": "h1",
"textBoxOpacity": 15
}
},
{
"name": "custom",
"content": "This is a complety different selection, yet there is no name to tell the difference between these two difference objects"
}
]
}

Loading Json as variable into jsTree

I am using jstree with Json. My problem is that I can provide the Json directly into jsTree data, but when I pass it as a variable it will print the entire Json string as the title of one node.
below is nodes.json
{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
}, {
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
}, {
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
}, {
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
},
this code below works
request = $.getJSON("nodes.json");
var data;
request.complete(function() {
data = request.responseText;
console.log(data);
$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
plugins: ["checkbox", "sort", "types", "wholerow", "search"],
"types": {
"file": {
"icon": "jstree-file"
}
},
'core': {
'data': [{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
}, {
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
}, {
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
}, {
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
}, ]
}
});
});
But this below does not work
request = $.getJSON("nodes.json");
var data;
request.complete(function() {
data = request.responseText;
console.log(data);
$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
plugins: ["checkbox", "sort", "types", "wholerow", "search"],
"types": {
"file": {
"icon": "jstree-file"
}
},
'core': {
'data': [data]
}
});
});
also if you would like to see the code execute I had it hosted on my domain.
http://www.jordanmclemore.com/projects/jstree/test/visual/current.html
In your original question data is a string (since you are using .responseText), to make it work as a variable, you should have used JSON.parse to convert the string to an array of objects.
Best regards,
Ivan
$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
plugins: ["checkbox", "types"],
"types": {
"file": {
"icon": "jstree-file"
}
},
'core': {
'data': {
'url': function(node) {
return 'nodes.json'
},
'data': function(node) {
return {
'id': node.id
};
}
}
}
});
I just followed Ivan's JSTree API more closely. His API is fantastic and following it closely will save you a lot of headache. ALSO, my json had a trailer comma I beleive and was invalid, so I had to fix that as well. I tested using a json validator.
I know you have already answered your own question, but I'd like to tell what's probably the cause of it anyway.
When looking at nodes.json you provided us with, I'd have to say that it isn't properly formatted as JSON. It is clearly an array, but not formatted as such. Thus you have multiple root elements, which is invalid JSON.
If you'd change nodes.json to this:
[{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
}, {
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
}, {
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
}, {
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
}]
And in your javascript:
request = $.getJSON("nodes.json");
var data;
request.complete(function() {
data = request.responseText;
console.log(data);
$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
plugins: ["checkbox", "sort", "types", "wholerow", "search"],
"types": {
"file": {
"icon": "jstree-file"
}
},
'core': {
'data': data
}
});
});
I think your problem would've been solved already.
Since your 'answer' doesn't fix the JSON, I'd say it's the wrong answer, and I advice you to try the things I suggested above.
By the way, a handy tool to validate your JSON with in the future:
http://jsonformatter.curiousconcept.com/
Please note that you may, or may not have to use $.parseJSON(data);

Get buckets average of a date_histogram, elasticsearch

I have the following query where get the a data and I create an aggregation of each past hour:
query = {
"query": {
"bool": {
"must": [
{ "term": {"deviceId":device} },
{ "match": {"eventType":"Connected"} }
],
"must_not":[{
"query_string": {
"query": "Pong",
"fields": ["data.message"]
}
},
]
},
},
"size": 0,
"sort": [{ "timestamp": { "order": "desc" }}],
"aggs" : {
"time_buckets" : {
"date_histogram" : {
"field" : "timestamp",
"interval" : "hour",
},
}
}
}
I would like to get the average of a field from each hour interval (each bucket created by the aggregation). In this article they talk about something similar with what I wish to do:
http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/_looking_at_time.html
("What was the average latency of our website every hour in the last week?"). However, they don't explain exactly what to do in this case.
Does anyone know how to do that?
Just realized that I could do a nested aggregation and then calculate the average of a field inside a aggregation. Here is what I did and it's working properly now:
query = {
"query": {
"bool": {
"must": [
{ "term": {"deviceId":device} },
{ "match": {"eventType":"Connected"} }
],
"must_not":[{
"query_string": {
"query": "Pong",
"fields": ["data.message"]
}
},
]
},
},
"size": 0,
"sort": [{ "timestamp": { "order": "desc" }}],
"aggs" : {
"time_buckets" : {
"date_histogram" : {
"field" : "timestamp",
"interval" : "day"
},
"aggs" : {
"avg_battery" : {
"avg": { "field": "data.battery-level" }
}
}
}
}
}

Using $.getJSON for getting json data in pagebeforeshow is not working in jquery mobile

i have used $.getJSON for getting json data on pagebeforeshow but it is not working as it have to.
$(document).on('pagebeforeshow', '#inpGrid', function(e) {
alert("inpGrid");
var tat_url = "http://192.168./html5/Demo/json/list.json";
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139&callback=?" ;
$.getJSON(tat_url, function(res) {
console.log(res)
});
});
the code is as above, when using url in $.getJSON it is working, wheras as using tat_url it is not working.
the http://192.168./html5/Demo/json/list.json consists as follows
{
"response": {
"respCode": 0,
"output": {
"delAction": "OP",
"delTmplt": "sibcVizEdit",
"title": "List TATs",
"layout": "grid",
"srvObjRef": "iawme1/IAWMblztnExpert-ListSIBCs_MB1412577249595",
"startIndex": "0",
"recsPerPage": "18",
"noPages": "1",
"curPageNo": "1",
"fieldInfo": [
{
"label": "Name",
"type": "STRING"
}
{
"label": "Alias",
"type": "STRING"
}
{
"label": "Datatype",
"type": "STRING"
}
{
"label": "Default Value",
"type": "STRING"
}
{
"label": "Visibility",
"type": "STRING"
}
],
"records": [
{
"Name": "psngrType"
"Alias": "Pasngr Type"
"Datatype": "STRING"
"Default Value":"CC"
"Visibility": "0"
},
{
"Name": "flightNo"
"Alias": "Flight No"
"Datatype": "STRING"
"Default Value":"$RV_flightNo"
"Visibility": "0"
}
],
"relServices": {
"AServices": [
{
"ref": "IAWMblztnExpert-ListSIBCs-UpdateBizContext_MB",
"title": "Update SIBC",
"desc": "",
"srvRef": "IAWMblztnExpert-ListSIBCs-UpdateBizContext_MB",
"slctdOffsets": "0"
},
{
"ref": "IAWMblztnExpert-ListSIBCs-ListIICsInSIBC_MB",
"title": "List IICs",
"desc": "",
"srvRef": "IAWMblztnExpert-ListSIBCs-ListIICsInSIBC_MB",
"slctdOffsets": "0"
},
{
"ref": "IAWMblztnExpert-ListSIBCs-Deploy SIBC_MB",
"title": "Deploy",
"desc": "",
"srvRef": "IAWMblztnExpert-ListSIBCs-Deploy SIBC_MB",
"slctdOffsets": "0"
}
]
}
}
}
}
Can someone help me please thanks.
Your JSON contain syntax errors, look your ''fieldInfo'' node. You didn't seperate your differents object by ,
Example:
{
"label": "Name",
"type": "STRING"
},
{
"label": "Alias",
"type": "STRING"
}
instead of
{
"label": "Name",
"type": "STRING"
}
{
"label": "Alias",
"type": "STRING"
}
Use online JSON validator if you need check rest of your json file easily : http://jsonlint.com/

Categories