Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Given the following JSON:
{
"api":{
"#api" : "{get}",
"method" : "/user/:id",
"message" : "Request User information"
},
"#apiName" : "GetUser"
}
How can I convert it to the following (API documentation) format?
/**
* #api {get} /user/:id Request User information
* #apiName GetUser
*/
Pretty simple. Just a matter of string concatenation and navigating the JSON object. Might be cleaner, if done with template strings.
function convertToDocumentationComment (json) {
var str = '/**\n'
str += ('* #api ' + json.api['#api'] + ' ' + json.api.method + ' ' + json.api.message + '\n')
str += ('* #apiName ' + json.api['#apiName'] + '\n')
str += '*/'
return str
}
Here's a test:
function convertToDocumentationComment (json) {
var str = '/**\n'
str += ('* #api ' + json.api['#api'] + ' ' + json.api.method + ' ' + json.api.message + '\n')
str += ('* #apiName ' + json.api['#apiName'] + '\n')
str += '*/'
return str
}
var json = {
"api":{
"#api" : "{get}",
"method" : "/user/:id",
"message" : "Request User information"
},
"#apiName" : "GetUser"
}
var r = convertToDocumentationComment(json)
document.write(r.replace(/\n/g, '<br>'))
I'm not sure if I'm correctly interpreting your question, but are you trying to generate documentation blocks of that using data from some JSON?
If so, you can use JSON.parse, then access the properties you need to build your string. I would probably use replaces in a template, like below (but that's far from the fastest method, I'm sure)
Your description of the format is missing, but you'll need to follow that to determine how to usethis.
var k = JSON.parse('{"#api" : "{get}"}');
var paramTpl = "* {name} {method} {message}\n";
var parameter = paramTpl.replace('{name}', k["#api"]);
Related
This is my very first question.
How can i run an "IF STATEMENT" in side the raw code of QZ tray where Var = print data [];
The below code works wonderful without IF STATEMENT, but the codes cannot parse once i use it.
var printData = [
'<xpml><page quantity="0" pitch="127.0 mm"></xpml>^AD\n',
'^O0\n'
'<xpml></page></xpml><xpml><page quantity="9" pitch="127.0 mm"></xpml>~MDELF,FORMAT_0\n',
'^E10.0\n',
'^L\n',
'C0,0000000000000000,+1,prompt_C0\n',
'C1,0000000000000000,+1,prompt_C1\n',
'C2,000,+1,prompt_C2\n',
'Lo,51,438,761,440\n',
'Lo,51,678,761,680\n',
'Lo,51,558,761,560\n',
'Lo,51,158,761,160\n',
'AH,320,31,1,1,0,0,'+ acs +'\n',
'BQ2,160,742,4,8,156,0,0,C^C0\n',
'AD,254,900,1,1,0,0,^C1\n',
'AA,439,440,1,1,0,0,Service\n',
'Lo,425,440,427,678\n',
'AA,442,560,1,1,0,0,Total No of Pieces\n',
'AA,439,684,1,1,0,0,Origin\n',
'AB,511,684,1,1,0,0,' + origin +'\n',
'AF,182,590,1,1,0,0,'+ destination+'\n',
'R49,13,762,999,3,3\n',
'E\n',
'^KFORMAT_0\n',
if (pcstart.length ==1)
{
premawb + postmawb +'0000'+ pcstart +'\n',
}
else {
premawb + postmawb +'000'+ pcstart +'\n',
}
pcstart + '\n',
'E\n',
'~P'+ copyPrint+'\n',
qz.print(config, printData).catch(displayError);
}
How can i run an "IF STATEMENT" in side the raw code of QZ tray
You can't mid-array, but you can add a ternary operator which does the same thing for a simple if/else statement:
pcstart.length == 1 ? '0000' : '000'
... and in context...
var printData = [
'<xpml><page quantity="0" pitch="127.0 mm"></xpml>^AD\n',
'...',
'^KFORMAT_0\n',
premawb + postmawb + (pcstart.length == 1 ? '0000' : '000') + pcstart + '\n',
pcstart + '\n',
'E\n',
'~P'+ copyPrint + '\n'
];
qz.print(config, printData).catch(displayError);
You can also call a function on the array element, so you may find it more desirable to roll your own pad(...) function and then call pad on the entire number or concatenated string... e.g:
premawb + postmawb + pad(pcstart, 4) +' \n',
I the above example, pad(...) is a function you make that can contain all the if/else statements you need and returns the formatted value.
I need to get field source from JSON but my solution not working !!
this is json:
"trailers":{
"quicktime":[],
"youtube":[{
"name":"BandeAnnonce",
"size":"HD",
"source":"RqEuaM9Fsrg",
"type":"Trailer"
}]
}
i try to get the source :var link_trailer = data.trailers[0].youtube[0].source;
but is not working for me !!
trailers is object, you don't need to use index.
var link_trailer = JSON.parse(data).trailers.youtube[0].source;
Try the following code
var text = '{' +
'"trailers": {' +
'"quicktime": [],' +
'"youtube": [{' +
'"name": "BandeAnnonce",' +
'"size": "HD",' +
'"source": "RqEuaM9Fsrg",' +
'"type": "Trailer"' +
'}]' +
'}' +
'}';
obj = JSON.parse(text);
var source = obj.trailers.youtube[0].source;
document.getElementById("demo").innerHTML ="Source field value is :"+source;
Here is the working jsfiddle:http://jsfiddle.net/NJMyD/5387/
Parse json into object first
var link_trailer = JSON.parse(data).trailers[0].youtube[0].source
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is a new edit to my question, hopefully it will meet the criteria and be considered eligible.
First, I managed to solve the problem. I will now describe the situation and what I think the solution that solve the problem.
My code gets a string (a call number) as an input, re-formats it, parse it to float, and return the call number location within a given set of ranges.
The code is composed of two functions: 1. formatCallNumber(callNum) which does the text manipulation to the input. 2. SortCallNum(callNumInput) - responsible on the sorting to ranges part.
The problem was in passing values of call number ranges from the sorting function (no.2) to the formatting function (no.1). Although I parsed those values as strings in the sorting function, the .replace function produced an error. The solution that I (think) worked, was to parse the values to strings in the formatting function.
The code of the two functions below is updated and seems to be working as expected:
function 1 - formatting function:
function formatCallNumber(callNum){
var formatedCallNum = String(callNum);
formatedCallNum = formatedCallNum.replace(/\D/g,''); // remove all but digits chars from the string (whitespace, dots, etc)
formatedCallNum = "0." + formatedCallNum; // add "0." to the callNumber string
formatedCallNum = parseFloat(formatedCallNum); // parse as float - so it could be compared with other decimals
return (formatedCallNum);
}
Function 2 - the sorting function:
function SortCallNum(callNumInput){
// data [test only]
var shelves = {
"S1" : {"callStart":"100","callEnd": "223.456", "id": 1},
"S2" : {"callStart":"223.457","callEnd": "334", "id": 2},
"S3" : {"callStart":"335","callEnd": "535", "id": 3},
"S4" : {"callStart":"536","callEnd": "638", "id": 4},
"S5" : {"callStart":"639","callEnd": "847", "id": 5}
};
var matchId = "";
document.getElementById("somthing").innerHTML += "you typed the number: " + callNumInput; // output of callNumInput (as inserted by user)
formatedCallNum = formatCallNumber(callNumInput);
// traverse into shelves object : iteration of objects (key = s1-s5)
for (var key in shelves) {
if (shelves.hasOwnProperty(key)) {
matchId = shelves[key].id;
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallEnd is: " + " -- " + shelves[key].callEnd); // display values of object shelves.key.callend
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallStart is: " + " -- " + shelves[key].callStart); // display values of object shelves.key.callend
var formatedCallRangeStart = formatCallNumber(shelves[key].callStart);
var formatedCallRangeEnd = formatCallNumber(shelves[key].callEnd);
console.log(formatedCallRangeStart);
console.log(formatedCallRangeEnd);
if ((formatedCallNum <= 0) || (formatedCallNum > 1)){alert('call number not in proper range'); break;}
if ((formatedCallRangeStart <= formatedCallNum)&&(formatedCallRangeEnd >= formatedCallNum)){break;}
}
}
Thanks for all the help.
As I can see, everythign should work as expected. It's important to pass a string into SortCallNum, and not a number.
function SortCallNum(callNumInput){
// data [test only]
var shelves = {
"S1" : {"callStart":100,"callEnd": "223", "id": 1},
"S2" : {"callStart":224,"callEnd": "334", "id": 2},
"S3" : {"callStart":335,"callEnd": "535", "id": 3},
"S4" : {"callStart":536,"callEnd": "638", "id": 4},
"S5" : {"callStart":639,"callEnd": "847", "id": 5}
};
var matchId = "";
document.getElementById("somthing").innerHTML += "you typed the number: " + callNumInput; // output of callNumInput (as inserted by user)
formatedCallNum = formatCallNumber(callNumInput);
// traverse into shelves object : iteration of objects (key = s1-s5)
for (var key in shelves) {
if (shelves.hasOwnProperty(key)) {
matchId = shelves[key].id;
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallEnd is: " + " -- " + shelves[key].callEnd); // display values of object shelves.key.callend
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallStart is: " + " -- " + shelves[key].callStart); // display values of object shelves.key.callend
var formatedCallRangeStart = String(shelves[key].callStart);
formatedCallRangeStart = formatCallNumber(formatedCallRangeStart);
var formatedCallRangeEnd = String(shelves[key].callEnd);
formatedCallRangeEnd = formatCallNumber(formatedCallRangeEnd);
matchId = shelves[key].id;
if ((formatedCallRangeStart <= formatedCallNum)&&(formatedCallRangeEnd >= formatedCallNum)){
break;
}
}
}
alert (matchId);
}
function formatCallNumber(callNum){
// callNum = prompt('enter a call number: ');
formattedCallNum = callNum.replace(/\D/g,''); // remove all but digits chars from the string (whitespace, dots, etc)
formattedCallNum = "0." + formattedCallNum; // add "0." to the callNumber string
formattedCallNum = parseFloat(formattedCallNum); // parse as float - so it could be compared with other decimals
return (formattedCallNum);
}
SortCallNum('1337')
<div id="somthing"></div>
So, this would work SortCallNum('1337'), this not SortCallNum(1337)...
Another possible cause is that you trust the return-value from prompt blindly.
<button type="button" onclick="var callNumInput = prompt('enter a call number: '); SortCallNum(callNumInput);"> SortCallNum(test)</button>
When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns null.
https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Example
A bit of sanitization should help:
if (callNumInput == null) {
throw new Error('You have to insert a number between 0 and 999.')
}
I am saving table data to a json object. The table data is coming from txt inputs and textareas in the table cells.
I'm running into a problem with CR/LF characters in the JSON elements holding the textarea data. The JSON data gets saved to the database fine, but when I pass it back to the jQuery function that populates the table using that data, I get this:
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 67 of the JSON data
var array = JSON.parse(notes),
in the console.
I put the JSON data in Notepad++ with Show All Characters on and the CR/LF was at column 67.
Here's a sample of JSON data that I'm working with:
[["","","",""],["","9/23/14","",""],["","30789 detail, x_vendor_no**CR/LF HERE**
20597 header","",""],["","99 del invalid x_vendor_no","",""],["","30780","",""],["","","",""],["","","",""],["","","",""]]
Is there a way to allow CR/LF in the data?
UPDATE
11684's suggestion to use replace to remove the \r part of the CRLF won't work. Here's why:
Here's the complete function that uses the JSON data:
(Updated to work with Update #2 code below)
function PopulateTaskTableWithNotes(tableID,notesArray) {
// JSON parse removed per answer suggestion
var r, c, note;
for (r = 0; r < notesArray.length; ++r) {
for (c = 0; c < notesArray[r].length; ++c) {
note = notesArray[r][c];
$('#' + tableID + ' tr:nth-child(' + (r + 1) + ') td:nth-child(' + (c + 1) + ')').children(':first-child').val(note);
}
}
}
I still get the error on the line that tries to parse the JSON data. The replace function apparently can't "find" characters within an array element.
UPDATE #2
Here's how I am creating the array:
var siteID = $('#ddlUserSites option:selected').val(),
numRows = $('#' + tableID + ' tr').length,
numCols = $('#' + tableID).find('tr:first th').length,
notesArray = new Array(numRows),
rowNum = 1,
note = '',
colNum;
while (rowNum <= numRows) {
notesArray[rowNum] = new Array(numCols);
// Reset colNum for next row iteration
colNum = 1;
while (colNum <= numCols) {
note = '';
if ($('#' + tableID + ' tr:nth-child(' + rowNum + ') td:nth-child(' + colNum + ')').children(':first-child').is('input,textarea')) {
note = $('#' + tableID + ' tr:nth-child(' + rowNum + ') td:nth-child(' + colNum + ')').children(':first-child').val();
}
notesArray[rowNum][colNum] = note;
//console.log('Note for rowNum ' + rowNum + ', colNum ' + colNum + ': ' + note);
colNum++;
}
// Remove first element in current row array
notesArray[rowNum].shift();
rowNum++;
}
// Remove first element in array
notesArray.shift();
JSON.stringify(notesArray); // Added per an answer here
console.log('Final notesArray: ' + $.toJSON(notesArray));
$.ajax({
data: {saveTaskNotes: 'true', userID:userID, siteID:siteID, taskTable:tableID, notes:notesArray},
success: function(data) {
console.log('Save task notes data: ' + data);
}
});
The "Final notesArray" console output looks fine, but now, with stringify added, the function above (PopulateTaskTableWithNotes) console output shows that it's reading through every character in the array as a separate element!
Maybe this will help too, as far as what's happening to the data between the creating and reading functions: the array is being saved to a single MySQL database field and then retrieved for the PopulateTable function via $.ajax() (on both ends).
Having said that, do I need to look at what I'm doing with/to the array in the PHP code?
UPDATE #3
Here's the PHP function that takes the data in and writes to the MySQL db:
function SaveTaskNotes($userID,$siteID,$taskTable,$notes) {
$notes = json_encode($notes);
$insertUpdateTaskNotesResult = '';
$insertTaskNotes = "INSERT INTO userProgress (userProgressUserID,userProgressSiteID,userProgressNotesTable,userProgressNotes) values ($userID,$siteID,'" . $taskTable . "','" . $notes . "')";
$log->lwrite('$insertTaskNotes: ' . $insertTaskNotes);
$resultInsertTaskNotes = #mysqli_query($dbc,$insertTaskNotes);
if ($resultInsertTaskNotes) {
$insertUpdateTaskNotesResult = 'insertTaskNotesSuccess';
} else {
if (mysqli_error($dbc) != '') {
$log->lwrite('INSERT TASK NOTES: An error occurred while attempting to add the task notes. Query: ' . $insertTaskNotes . ', mysqli_error: ' . mysqli_error($dbc));
}
$insertUpdateTaskNotesResult = 'insertTaskNotesFail';
}
echo $insertUpdateTaskNotesResult;
}
And here's the function that gets the data from the db and sends it to the above $.ajax function:
function GetUserTaskNotes($userID,$siteID,$taskTableID) {
$queryGetUserTaskNotes = "SELECT userProgressNotes FROM userProgress WHERE userProgressUserID = $userID AND userProgressSiteID = $siteID AND userProgressNotesTable = '" . $taskTableID . "'";
$log->lwrite('$queryGetUserTaskNotes: ' . $queryGetUserTaskNotes);
$resultGetUserTaskNotes = #mysqli_query($dbc,$queryGetUserTaskNotes);
if ($resultGetUserTaskNotes) {
$taskNotes = mysqli_fetch_assoc($resultGetUserTaskNotes);
$log->lwrite('Retrieved $taskNotes[\'userProgressNotes\']: ' . $taskNotes['userProgressNotes']);
echo $taskNotes['userProgressNotes'];
} else {
if (mysqli_error($dbc) != '') {
$log->lwrite('GET TASK NOTES: An error occurred while attempting to retrieve the task notes. Query: ' . $queryGetUserTaskNotes . ', mysqli_error: ' . mysqli_error($dbc));
}
echo 'getTaskNotesFail';
}
}
In both the save and get functions the $log output shows that the array never changes (with the above js/php code) and pasting the array in to notepad++ shows that the CR/LF is still there throughout.
Don't use JSON.parse, the data is already JSON and Javascript can work with it.
You only need it when passing a string, imagine JSON.parse() beeing like string2json().
I think this might already be a solution to your problem, I've never had issues with new line characters.
As Luis said, the problem is not your client (Javascript, jQuery), besides the JSON.parse, but the providing site is wrong.
Example for PHP:
<?php
echo json_encode(array("test" => "
x"));
PHP properly escapes the characters:
{"test":"\r\n\r\n\r\nx"}
But the source of your data is providing malformed JSON.
To fix the JSON issue, either use prepared statements or use:
$notes = str_replace('\', '\\', json_encode($notes)); // in SaveTaskNotes
Well, the error is on the input data (showed in question). You can't have an CR or LF inside a literal in a JSON string. What you can have are that chars escaped as \r \n. The problem is on other side, where escaped codes are replaced by actual chars and therefore the full JSON string becomes invalid.
This question already has answers here:
Access Javascript variables dynamically
(4 answers)
Closed 8 years ago.
I know there are a lot of questions about if it is possible to use variable variables in jQuery.
One of the questions is this one: click here.
I tried to use the answer, but I don't know how I can use it in my case.
var numberofquestions = 10;
var dataString = "";
for ( var i=1; i<=numberofquestions; i++ ) {
/* ------ first part ------- */
if (i==1) {
dataString = dataString + "q1=" + question1 + "&";
} /* ------ end first part ------- */
else if (i == numberofquestions) {
questionValue = "question" + numberofquestions;
qValue = "q" + numberofquestions;
dataString = dataString + qValue + "=" + questionValue;
console.log(dataString);
} else {
questionValue = question + i;
dataString = dataString + "q" + i + "=" + questionValue + "&";
}
}
The loop will run 10 times, and each time it needs to add a part to the already existing dataString.
What it needs to do is make this string:
q1=(value of var question1)&q2=(value of var question2) and so forth.
The vars question1, question2, ... question10 all hold a number.
The first part works, it outputs q1=5 in the console log, however, after comes a random string. The output string (the total string) looks like:
q1=5&q2=NaN&q3=NaN&q4=NaN&q5=NaN&q6=NaN&q7=NaN&q8=NaN&q9=NaN&q10=question10
Does anybody know what I'm doing wrong?
You should use an array for this. There is no such thing as "variable variables" in JavaScript.
You can access a variable through a string containing the variables name by using this[variableName], but again, you shouldn't. You should use an array for this.
In your case, you would use questionValue = this["question" + i], but one more time: Don't do it. Use an array instead.
I'm not sure why you're using "question" + numberofquestions which will be 10 every time