is it possible to have a for loop in JSRender with incremental variable i? - json

i have template (an html file) with is getting renders with JSON data using JSRender.
My Sample Template is as follows
<ul id="membersList">
{{for UserConnection}}
<li>
<div>
<a title="{{:Fullname}}">
<br />
<img src="sample.png"/><br />
{{:Fullname}}</a>
</div>
</li>
{{/for}}
My Json data is
[
{
"ApplicationName": "appone",
"Title": "Title one",
" UserConnection ": [
{
"Id": 210,
" email ": " abc1#xyz.com ",
},
{
"Id": 0,
" email ": " ",
},
{
"Id": 211,
" email ": " abc2#xyz.com ",
}
]
}
];
Now my requirement is the i should hide of div if in particular the 2nd item of
the JSON has the its id value as 0.
Is it possibel in JSRender to check some thing which we do in c# like
for (i = 0 ; i < 10 ; i++)
{
if (userConnection[i] = 0)
// show the div
else
// dont show
}
i.e. if i can access UserConnection[i] even in JSRender, then i can show or hide the div.
Is it possible?

You can look at this example to see how to get to the parent data https://www.jsviews.com/#parentdata
and there is #index while in the for loop to get access to the current index.
I think really the answer to your question is to use a helper to construct the div with either display on or off at the time it is created.
A helper, converter, and customer tags are all general javascript functions that you register and then use.

Related

Bad JSON escape sequence: \\1. Path 'sections[0].facts[0].value', line 1, position 196."

Am getting getting Bad JSON escape sequence: \\1. Path 'sections[0].facts[0].value', line 1, position 196." while parsing json string with string.Format to add data based on placeholder.
Below is the code :
string jsonFormatString = #"{{""title"": ""{0}"",""sections"": [{{""facts"": [{{""name"": ""TransactionNo"",""value"": ""{1}""}}]}}]}}";
string formattedJson= string.Format(jsonFormatString , message, transactionNo ?? "");
var result = JsonConvert.DeserializeObject<dynamic>(formattedJson);
The string values for placeholders were message = "Transaction Success", transactionNo = "1920\01\ABC";
Looks like escape character transactionNo field is creating problem.
I tried with string.Replace(#"\\", #"\") and others nothing helped in resolving the error.
If i added string.Replace(#"\", #"\\", it works but result json contains transactionNo as "1920\\01\\ABC" which is also wrong.
Am i missing something or should i add anything more
I have seen folks do this in the past and even had to maintain code that looks like this... and as you are experiencing: It is a huge PITA.
You can easily lay out your objects using anonymous types so they are simple to maintain and understand for the folks who may have the pleasure to work with your code in the future.
Take a look at this:
var myObj = new {
title = "<input value>",
sections = new[]
{
new
{
facts = new[]
{
new
{
name = "TransactionNo",
value = "<input value>"
}
}
}
}
};
var result = JsonConvert.SerializeObject(myObj, Formatting.Indented);
Result will look like this:
{
"title": "<input value>",
"sections": [
{
"facts": [
{
"name": "TransactionNo",
"value": "<input value>"
}
]
}
]
}
Now, keep in mind that this is easier to maintain than formatting a string, but at the end of the day it's better to just bite the bullet and create some concrete models.

Updating a Highly Nested Document in Couchbase

I have a document that contains multiple levels of hierarchy. Something like this:
{
"id": "520707438",
"pageURIHash": "3988665684",
"children": [],
"parentId": null,
"content": "Here is a parent comment"
}
The children array may have other child comments as JSON objects, and each of the child in turn may have other children. Thus, this forms a highly nested structure.
Now, suppose I want to add a child comment to a comment with ID as 123456745. I am assuming that I know the root-level comment (so that I can use the USE KEYS clause in my N1ql query). How do I extract the children array corresponding to the comment with that particular Id and append a new comment to it? I could use the sub-document API but it requires me to know the path, and in this case, I do not know it.
I did a bit of research and came up with this query:
"UPDATE default d use keys \"" + comment.getRootCommentId()
+ "\" SET (??? How do I get the existing array and append to it) FOR p WITHIN d.children WHEN p.id = \"" + comment.getId() + "\" END";
Thanks a lot!!
This should do what you want:
update default d use keys "foo"
SET p.children = ARRAY_APPEND(p.children, {
"id": "20202020",
"pageURIHash": "99999",
"children": [],
"parentId": null,
"content": "New Stuff"
}) FOR p WITHIN d.children WHEN p.id = "520707440" END

Pug - mixin with conditional .json object

I'm trying to use a conditional (if exists an object at a external .json), but pug doesn't recognize it.
So, my json file is something like this:
{
"portfolioItems": [object1: {
objectA { ...
},
objectB { ...
},
"buttons": [{
key: value
}, {
key: value
}]
}, object2: {
objectA { ...
},
objectB { ...
}], object3: {
objectA { ...
},
objectB { ...
}
}
}
}
Basically, I need to create an extra div for "object 1" (buttons).
mixin portfolio(css, image, title, description)
div(class= "item " + css)
.wrap-img
img(src= assets + "img/home/" + image)&attributes(attributes)
.wrap-text
h3= title
p= description
if home.portfolioItems.buttons
div.buttons
each val in home.portfolioItems.buttons
a(href= val.link, target="_blank")
img(class= val.className, src= assets + "img/stores/" + val.image)
div.portfolio--items
- var projects = home.portfolioItems;
each item in projects
+portfolio(item.class, item.image, item.title[lang], item.description[lang])(alt= item.title[lang], title=item.title[lang])
Pug can access to "home.portfolioItems.buttons", but it can't do a conditional inside a mixin? Because I can run it outside (but I don't want it).
Thanks in advance. Sorry any mistake in english. ;)
Mixins have their own scope, so you'll need to pass them in an object. I'd also recommend a single options object which makes this a lot easier than tracking separate parameters, is order-independent, and is more readable too.
Note that you can call a mixin and span multiple lines with the definition
+portfolio({
"css": "css",
"image": "image",
"title": "title",
"description": "description",
"items": portfolioItems
})
This is what the mixin would look like:
mixin portfolio(options)
div(class= "item " + options.css)
.wrap-img
img(src= assets + "img/home/" + options.image)&attributes(options.attributes)
.wrap-text
h3= options.title
p= options.description
if options.items.buttons
div.buttons
each val in options.items.buttons
a(href= val.link, target="_blank")
img(class= val.className, src= assets + "img/stores/" + val.image)
You could also avoid passing in all the items and pass in the buttons OR an empty array if the buttons property doesn't exist in portfolioItems:
+portfolio({
"css": "css",
"image": "image",
"title": "title",
"description": "description",
"buttons": portfolioItems.buttons || []
})
Which would avoid the need for the conditional test as you're guaranteed at least an empty array in the mixin:
mixin portfolio(options)
div(class= "item " + options.css)
.wrap-img
img(src= assets + "img/home/" + options.image)&attributes(options.attributes)
.wrap-text
h3= options.title
p= options.description
div.buttons
each val in options.buttons
a(href= val.link, target="_blank")
img(class= val.className, src= assets + "img/stores/" + val.image)

Notepad++: What is the "opposite" format of JSFormat?

I'm looking for the "opposite" Format of JSFormat from the JSTools. Here an example:
JSON code example:
title = Automatic at 07.02.17 & appId = ID_1 & data = {
"base": "+:background1,background2",
"content": [{
"appTitle": "Soil",
"service": {
"serviceType": "AG",
"Url": "http://test.de/xxx"
},
"opacity": "1"]
}
],
"center": "4544320.372869264,5469450.086030475,31468"
}
& context = PARAMETERS
and I Need to convert the Format to the following format:
title=Automatic at 07.02.17 &appId=ID_1&data={"base":"+:background1,background2","content":[{"appTitle":"Soil","service":{"serviceType":"AG","Url":"http://test.de/xxx"},"opacity":"1"]}],"center":"4544320.372869264,5469450.086030475,31468"}&context=PARAMETERS
which is a decoded URL (with MIME Tools) from this html POST:
title%3DAutomatic%20at%2007.02.17%20%26appId%3DID_1%26data%3D%7B%22base%22%3A%22+%3Abackground1,background2%22,%22content%22%3A%5B%7B%22appTitle%22%3A%22Soil%22,%22service%22%3A%7B%22serviceType%22%3A%22AG%22,%22Url%22%3A%22http%3A%2F%2Ftest.de%2Fxxx%22%7D,%22opacity%22%3A%221%22%5D%7D%5D,%22center%22%3A%224544320.372869264,5469450.086030475,31468%22%7D%26context%3DPARAMETERS%0D%0A
which I have to come back after doing changes in the JSON code. From the second to the third Format I can use URL encode (MIME Tools), but what about the reformating from the first to the second Format.
My question: Do you have ideas how to turn the first (JSON) Format into the second (decoded URL) in Notepad++? Something like the "opposite" of JSFormat?
If I understand correctly you basically need to put your JSON on a single line removing new lines and spaces.
This should be achieved with these steps:
CTRL + H to replace occurrences of more than one space with empty string using this regex: [ ]{2,} (remember to select "Regular expression" radiobutton). If this is not exactly what you want you can adjust the regular expression to achieve desired output
select all your JSON CTRL + A
put everything on a single line with join CTRL + J
You can also record a macro to automate this process and run it with a keyboard shortcut.

How to map a data to a segment if the data is not in a collection in Kony Studio?

I am using Kony Studio 5.5 for cross platform development. I retrieve data by using a JSON service. I want to print my data in a segment, but I can't map some of it because it is not in a collection.
"chartStat": " CHART NOT PREPARED ",
"passengers": [{
"trainBookingBerth": "RAC9 , 8,GN ",
"trainCurrentStatus": " CNF ",
"trainPassenger": "Passenger 1"
}],
"trainBoard": "Kovilpatti",
"trainBoardCode": "CVP",
"trainDest": "Chennai Egmore",
In the above payload I can map passengers to the segment but I also want to map trainBoard, trainBoardCode and trainDest to it.
If you are using the Kony service editor, parse the output according to your requirement. By parsing the result one can isolate the required parameter -i.e.: Filter the result returned from service- that are only required at the client side and in a format that we can specify.
If you have three labels in the segment and you want to show the passengers details return by the service, please follow these steps:
Parse your JSON data, while mentioning the id in the service editor, please keep in mind to use the id of the children widgets of the segment as the id for output parameter.
After parsing the you must get a collection which is similar as following
[
{ "labelOneId": "RAC1 , 8,GN ", "labelTwoId": " CNF 1", "labelThreeId": "Passenger 1" },
{ "labelOneId": "RAC2 , 8,GN ", "labelTwoId": " CNF 2", "labelThreeId": "Passenger 2" },
{ "labelOneId": "RAC3 , 8,GN ", "labelTwoId": " CNF 3", "labelThreeId": "Passenger 3" },
{ "labelOneId": "RAC3 , 8,GN ", "labelTwoId": " CNF 4", "labelThreeId": "Passenger 4" }
]
Where the labelOneId, labelTwoId and labelThreeId will be the ids used for children of the segment where the data need to be displayed.
After this use the set data method of the Kony.ui.segment widget to set the data.
Note: If you did not use the id of the children widget then you will have to format the data using a "for" loop iterator.
Extracting the value from the sample value provided in your question:
var jsonReturned={
"chartStat": " CHART NOT PREPARED ",
"passengers": [{
"trainBookingBerth": "RAC9 , 8,GN ",
"trainCurrentStatus": " CNF ",
"trainPassenger": "Passenger 1"
}],
"trainBoard": "Kovilpatti",
"trainBoardCode": "CVP",
"trainDest": "Chennai Egmore"
};
var oneVal = jsonReturned["passengers"]["0"]["trainBookingBerth"];
var twoVal = jsonReturned["passengers"]["0"]["trainCurrentStatus"];
var threeVal = jsonReturned["passengers"]["0"]["trainPassenger"];
var fourVal = jsonReturned["trainBoard"];
var fiveVal = jsonReturned["trainDest"];
var dataForSegment = [{
"labelOneId": oneVal,
"labelTwoId": twoVal,
"labelThreeId": threeVal,
"lableFourId": fourVal,
"labelFiveId": fiveVal
}];
Try setting this in the as the dataForSegment as segment data. If you want to add any additional value you have to similarly extract the data from the JSON object and form a collection suitable for your segment.
This question was asked a very long time ago, but for anyone wondering how to do this, you can use the addDataAt and setDataAt methods you can use to respectively insert or replace a single row of data at a specified position in a Segment.
From Kony's Widget Programmer's Guide about the addDataAt method:
Allows you to add one row of data at a given index or within a section.
addDataAt(data, rowIndex, sectionIndex)
and about the setDataAt method:
Allows you to set data or modify an existing data of a row or within a section.
setDataAt(data, rowIndex, sectionIndex)
I hope this helps others in the future.
You need to follow this structure to put data in Segment...
var data=[
[{lblHeading:"Section1"},[{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"}]],
[{lblHeading:"Section2"},[{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"}]],
[{lblHeading:"Section3"},[{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"}]],
[{lblHeading:"Section34"},[{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"},{samplelabel:"1"}]]
];
this.view.segmentList.setData(data);