I have this jade template:
html
head
script(type="text/javascript" src="https://www.google.com/jsapi")
script(type='text/javascript')
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Tin_A' ],
- each datapoint in myData
"[" + datapoint.date + "," + datapoint.value + "],"
]);
var options = {
title: 'bla'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_line'));
chart.draw(data, options);
}
body
h1= title
#chart_line
and I'm using this call to render the jade template in express/node.js:
app.get('/', function(req, res){
sensors.findSensorAllData(2, 2, function (error,emps){
console.log(emps);
res.render('tmp', {
title : 'Temperatures in a row',
myData : emps
});
});
});
the output of the console.log(emps) is:
[ { _id: 524b8642028e167fb0e3661d,
sensor_id: 2,
value: 49,
date: Tue Oct 01 2013 20:34:40 GMT-0600 (CST) },
{ _id: 524b863d028e167fb0e3661c,
sensor_id: 2,
value: 19,
date: Tue Oct 01 2013 20:34:35 GMT-0600 (CST) } ]
after the rendering occour, I expect to have the values within the javascrip in the jade template... but It won't work. I get only the same lines in plain text, as if the line - each datapoing in myData would have no meaning... what am I doing wrong? Thanks
--- Edit:
Everything works fine if I replace the lines
- each datapoint in myData
"[" + datapoint.date + "," + datapoint.value + "],"
with
['2004', 20],
['2005', 30],
['2006', 40]
I think you may be accidentally injecting a String instead of an Array because of the quotes around the brackets:
- each datapoint in myData
"[" + datapoint.date + "," + datapoint.value + "],"
I'm not very familiar with Jade, but I think you may want to do the following instead:
- each datapoint in myData
[#{datapoint.date}, #{datapoint.value}],
Also, in the sample data you gave that works, you are only using the year portion of the Date, but the contents of the datapoint.date property may be a full Date object, I'm not sure if that is what you want for this use.
See this question's chosen answer for why what you're trying to do doesn't work. (JADE + EXPRESS: Iterating over object in inline JS code (client-side)?)
Basically, as soon as you hit the script tag, you're telling the Jade parser to handle things in raw form, and no further processing is done. What you really want to do is redo the script tag for your code like follows:
- if (typeof(pins) != "object")
!= "<script type='text/javascript'>"
!= "google.load('visualization', '1', {packages:['corechart']});
!= "google.setOnLoadCallback(drawChart);
!= "function drawChart() {
!= "var data = google.visualization.arrayToDataTable([
!= "['Date', 'Tin_A' ],"
- forEach datapoint in myData
!= "[" + datapoint.date + "," + datapoint.value + "],"
!= "]);"
!= "var options = {"
!= "title: 'bla'"
!= "};"
!= "var chart = new google.visualization.LineChart(document.getElementById('chart_line'));"
!= "chart.draw(data, options);"
!= "}"
Try this, but I'm fairly certain it should work.
PS: The link above also (I believe) clearly states why the previous answer should be incorrect, as you can't have that kind of template placeholder interpolation inside of Jade script tags.
Ugly alert:
script
...
var data = google.visualization.arrayToDataTable(['Date', 'Tin_A' ].concat(!{JSON.stringify(myData.map(function(i) { return [ i.date, i.value ] })) }));
Related
i want to convert a .csv file and write a new one. However I am not able to remove the first , i am kinda stuck here and it is driving me crazy.
This is my code:
var extractedtasks = tasks.slice(0, 3)
var extractedtasksformated = extractedtasks.toString().replace(/,$/g, "\n")
let csvformat = "EMAIL,PASSWORD,MAILBOX"
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksformated.replace(/,^/g,
""))
console.log(chalk.green("Successfully updated the CSV file"))
That's the output i am getting in the newly generated file
EMAIL,PASSWORD,MAILBOX
example1#gmail.com,Password123,example#gmail.com:password
,example2#gmail.com,Password123,example#gmail.com:password
,example3#gmail.com,Password123,example#gmail.com:password
Output extractedtasks:
[
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
Output extractedtasksformated:
,example3#gmail.com,Password123,example#gmail.com:passwordxample#gmail.com:password
Because extractedtasks is an array, instead of converting it to a string you should just join it with the expected separator:
extractedtasks = [
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
extractedtasksJoined = extractedtasks.join("\n")
// "example1#gmail.com,Password123,example#gmail.com:password\r\nexample2#gmail.com..."
// depending on the target line separator, you should also probably
// remove the "\r"
extractedtasksJoined = extractedtasksJoined.replace("\r", "")
// finally
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksJoined + "\n")
I'm exporting json files to csv using Filesaver.js and json-export-excel.js. The comma separator is causing the columns to shift when it sees a comma in the string.
Plunker Demo
How can i ignore commas found within string?
<button ng-json-export-excel data="data" report-fields="{name: 'Name', quote: 'Quote'}" filename ="'famousQuote'" separator="," class="purple_btn btn">Export to Excel</button>
JS File:
$scope.data = [
{
name: "Jane Austen",
quote: "It isn\'t what we say or think that defines us, but what we do.",
},
{
name: "Stephen King",
quote: "Quiet people have the loudest minds.",
},
]
Current CSV output (Not Desired): (Note: | marks the columns in csv file)
Name Quote
Jane Austen | It isn't what we say or think that defines us| but what we do.|
Stephen King| Quiet people have the loudest minds. | |
Desired CSV output:
Name Quote
Jane Austen | It isn't what we say or think that defines us, but what we do.|
Stephen King| Quiet people have the loudest minds. |
For Excel, you need to wrap values in quotation marks. See this question.
In json-export-excel.js you'll see that the _objectToString method wraps the output in quotes but because the fieldValue variable isn't an object this is never called for this example.
function _objectToString(object) {
var output = '';
angular.forEach(object, function(value, key) {
output += key + ':' + value + ' ';
});
return '"' + output + '"';
}
var fieldValue = data !== null ? data : ' ';
if fieldValue !== undefined && angular.isObject(fieldValue)) {
fieldValue = _objectToString(fieldValue);
}
If you add an else statement to this to wrap the value in quotes, the CSV opens in Excel as desired.
} else if (typeof fieldValue === "string") {
fieldValue = '"' + fieldValue + '"';
}
Plunker
I have the following object
{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
}
loaded from a text file abc.txt in my local directory in the server.
I want to convert this into an array object. I tried doing
var string = "{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
}"
var array = JSON.parse("[" + string + "]");
alert(array);
Nothing happens unfortunately. Help appreciated !
You can use "eval" to accomplish what you are attempting.
var s = '{value: 20, color:"#878BB6" },' +
'{value : 40, color : "#4ACAB4"}';
var arr = eval('[' + s + ']');
alert(arr[0].value);
Also, in order for JSON.parse to parse it the string needs to be valid JSON. So you'll need to have quotes around the object property names. Like the following:
var s = '{"value": 20, "color":"#878BB6" },' +
'{"value": 40, "color": "#4ACAB4"}';
var arr2 = JSON.parse('[' + s + ']');
alert(arr2[1].value);
Although it would be better to modify the process for generating the text file to contain valid JSON if you can. Then you could use jQuery or some other method of just loading the JSON from the file directly.
I found a script that's used to extract saved articles from Feedly (by running it inside Chrome's Inspect Element console), but I'd like to tweak it a bit for my needs. I'm not a developer or anything like that so I'd appreciate it if someone could help!
Here's part of the script:
json = ""
function copyToClipboard() {
// Loop through the DOM, grabbing the information from each bookmark
map = jQuery("#section0_column0 div.u0Entry.quicklisted").map(function(i, el) {
var $el = jQuery(el);
var regex = /published:(.*)\ --/i;
return {
title: $el.data("title"),
url: $el.data("alternate-link"),
time: regex.exec($el.find("div.lastModified span").attr("title"))[1]
};
}).get(); // Convert jQuery object into an array
// Convert to a nicely indented JSON string
json = JSON.stringify(map, undefined, 2)
Here's an example of what it returns:
[
{
"title": "Blog post headline",
"url": "http://urlofblogpost.com/article",
"time": "Tue, 10 Dec 2014 21:00:00 GMT"
},
{
"title": "Blog post2 headline",
"url": "http://urlofblogpost.com/article2",
"time": "Tue, 10 Dec 2014 21:00:00 GMT"
},
]
Here's what I'd like it to return:
Blog post headline
Blog post2 headline
The most I could do on my own was delete the "time" part from the script, remove the brackets, and isolate the titles and URLs (using a text editor):
Blog post headline
http://urlofblogpost.com/article
Is there any way to change the script to get it in links?
Just Iterate through the json:
Javascript:
function copyToClipboard() {
// Loop through the DOM, grabbing the information from each bookmark
map = jQuery("#section0_column0 div.u0Entry.quicklisted").map(function(i, el) {
var $el = jQuery(el);
var regex = /published:(.*)\ --/i;
return {
title: $el.data("title"),
url: $el.data("alternate-link"),
time: regex.exec($el.find("div.lastModified span").attr("title"))[1]
};
}).get(); // Convert jQuery object into an array
var theLink = '';
$.each(yourJson, function(k,v){
theLink += "<a href=" + v.url + " >" + v.title + " </a>, \n";
});
window.prompt('my link', theLink);
I create js fiddle for you play: http://jsfiddle.net/reptildarat/GG5BP/4/
Update: I tried a version of the script without the "beforeContentUpdate" part, and this script returns the following JSON
{"COLUMNS":["TNAME","TBRIEF","GAMEID","TITLEID","RDATE","GNAME","PABBR","PNAME","RSCORE","RNAME"],
"DATA":[["Dark Void","Ancient gods known as 'The Watchers,' once banished from our world by superhuman Adepts, have returned with a vengeance.",254,54,"January, 19 2010 00:00:00","Action & Adventure","X360","Xbox 360",3.3,"14 Anos"]]}
Using the script that includes "beforeContentUpdate," however, returns nothing. I used Firebug to see the contents of the div generated by the tooltip, and it's blank!
Hello, I'm wondering if anyone can help me with a syntax error in line 14 of this code:
The debugger says missing ) in parenthetical on var json = eval('(' + content + ')');
// Tooltips for index.cfm
$(document).ready(function()
{
$('#catalog a[href]').each(function()
{
$(this).qtip( {
content: {
url: 'components/viewgames.cfc?method=fGameDetails',
data: { gameID: $(this).attr('href').match(/gameID=([0-9]+)$/)[1] },
method: 'get'
},
api: {
beforeContentUpdate: function(content) {
var json = eval('(' + content + ')');
content = $('<div />').append(
$('<h1 />', {
html: json.TNAME
}));
return content;
}
},
});
});
});
You forgetting a
+
Should be:
var json = eval('(' + content + ')');
the best for this is www.jslint.com
i'd copied and paste your code and show me this:
Problem at line 21 character 10: Extra
comma.
},
Make sure you JSON has no extra characters, the JSON must be valid. Check how the content returns with a plain alert so nothing will change the string.
Also, consider using parseJSON from jQuery instead of eval. Quote:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
This turned out to be another case where the ColdFusion debugger, when request debugging output is turned on, causes an ajax error. This is one big "gotcha" we need to remember when working with ColdFusion with debugging enabled. It breaks down ajax.