I am trying to form an array from a string using Modified Java Script Value step. Here is my code to parse a string and to form a JSON object.
var info = {};
var keywords = 'Adjust course (C-6),Identify underlying factors (C-4),Isolate teacher actions (C-3_)';
if(keywords != null && keywords != ''){
keywords = keywords.replace(/,/g,'","');
keywords = '["'+keywords+'"]';
info.keywords = JSON.parse(keywords);
}
Here in JSON.parse() it throws an error SyntaxError: Missing comma in array literal.
Can anyone please help me parse the array and store in json object.
Thanks in advance!
Try this one
if(keywords){
keywords = keywords.split(',');
info.keywords = keywords;
}
Try this:
function kwInfo(text)
{
return JSON.parse('["' + (text || '').split(',').join('","') + '"]');
}
var text = 'Adjust course (C-6),Identify underlying factors (C-4),Isolate teacher actions (C-3_)';
var info = {keywords:kwInfo(text)};
console.log(info);
Run kettle in console mode SpoonConsole.bat
var info = {};
var keywords = 'Adjust course (C-6),Identify underlying factors(C-4),Isolate
teacher actions (C-3_)';
java.lang.System.out.println("Original : " + keywords);
if(keywords != null && keywords != ''){
keywords = keywords.replace(/,/g,'","');
java.lang.System.out.println("Regexp applied : " + keywords);
keywords = '["'+keywords+'"]';
java.lang.System.out.println(keywords);
info.keywords = JSON.parse(keywords);
}
Look into console and trace the error in logic
This is only way I found to trace JavaScript step
Related
unable to get the value_1 from dataObject.Showing undefined.
var errorMessage;
var dataObject ={"project_type":"{\"value_1\":\"Ground Mount\"}"};
var project_type_str = dataObject['project_type'];
project_type_str = JSON.stringify(project_type_str);
if (project_type_str != null && project_type_str.length != 0) {
errorMessage = '';
} else {
errorMessage = 'Please select a project type';
}
alert(project_type_str);
var responseJson = {};
var project_type_obj = JSON.parse(project_type_str);
alert(project_type_obj);
var value = project_type_obj["value_1"];
alert(value);
Thanks for your answers.Please help me
project_type_str is already a string, so no need to JSON.stringify it.
The code should work fine if you remove the line
Remove this line
project_type_str = JSON.stringify(project_type_str);
A comparison for your better understandability
With original code
With the line removed
You don't need those extra quotes and escape characters to define the object. Do this:
var dataObject = {
"projectType": {
"value1": "groundMount"
}
};
EDIT: I now see that you were intentionally writing JSON in its string representation so that you can parse it later. I hope that you have a special use case where you'd need to do something like that; otherwise, defining the object like I have will be much easier to deal with.
Grab the substring:
var hash = document.location.hash;
// create an object to act like a dictionary to store each value indexed by its key
var partDic = {};
// remove the leading "#" and split into parts
var parts = hash.substring(1).split('&');
// If you just want the first value, whatever it is, use this.
// But be aware it's a URL so can be set to anything in any order, so this makes little sense
// var string = parts[0].split('=')[1];
// build the dictionary from each part
$.each(parts, function(i, v) {
// do the "=" split now
var arr = v.split("=");
// decode to turn "%5B" back into "[" etc
var key = decodeURIComponent(arr[0]);
var value = decodeURIComponent(arr[1]);
// store in our "dictionary" object
partDic[key] = value;
});
// Set a delay to wait for content to fully load
setTimeout( function() {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
var cl = partDic["comboFilters[Clients]"].substring(1);
$('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
$('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
}, 1000);
But if there is not a substring, I am getting:
Uncaught TypeError: Cannot read property 'substring' of undefined
Suggested answer in another question
var cl = (partDic["comboFilters[Clients]"] && partDic["comboFilters[Clients]"].length>0)?partDic["comboFilters[Clients]"].substring(1):'';
But I still get the same error
You can be defensive and check if a key exists before using it:
if("comboFilters[Agencies]" in partDic) {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
}
or just safeguard it with an empty string:
var ag = (partDic["comboFilters[Agencies]"] || "").substring(1);
Maybe try with things like:
var parts = (hash && hash.substring(1).split('&')) || [];
You can try to check it's type:
var cl = (typeof partDic["comboFilters[Clients]"] === 'string')?partDic["comboFilters[Clients]"].substring(1):'';
Note, that you should add this check for all your variables: ag, cl, yr
You can check one condition before using substring method..
if((!hash) || (!hash.substring(1)){
return false;
}
I imported json data into google scripts with:
var doc = Utilities.jsonParse(txt);
I can access most of the objects like such...
var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;
A bunch of objects I need to access have numbers as object names...
doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata
...but when I try to read the data with...
var teamId = doc.data2.personal.team.87397394;
... I get an error "Missing ; before statement."
I tried this...
var teamId = doc.data2.personal.team[87397394];
... and get "teamId undefined" in the log.
I also tied this with the same result...
var teamId = doc.data2.personal.team[+'6803761'];
I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.
Thank you!
Brian
UPDATE
I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...
for(var propertyName in doc.data2.personal.team) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
Logger.log (propertyNames);
var test = doc.data2.personal.team[propertyName];
}
The log shows the object names, as expected...
87397394
87397395
87397396
87397397
I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...
function myFunction1() {
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = Utilities.jsonParse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
Logger.log (propertyName);
var test = doc.datablock_battle_result.vehicles[propertyName];
}
}
The problem seems to be in the Utitlies.jsonParse. The following works fine
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
var vehicle = doc.datablock_battle_result.vehicles[propertyName];
Logger.log('Vehicle id is ' + propertyName);
Logger.log('Vehicle value is ' + JSON.stringify(vehicle));
break;
}
This is the code I have
<script>
function validation () {
var x=document.getElementById("user").value;
var y=document.getElementById("user");
var names="<%=names%>";
for (var j=0; j<names.length; j++) {
if (names[j].test(x)) {
//alert(names[j].match(x));
return true;
}
else{
y.focus();
return false;
}
}
}
</script>
This is for a login page,2 fields are there as usual username password.
I am checking if the username is there in the database,he can enter the password or else he cant.But this code doesnt go to the password even if the username is right.
What am I doing wrong?
Suppose the data type of names in java is an String[], the code <%=names%> equals to <%=names.toString()%>.
So when the jsp is rendered, your javascript code will be something like var names="[Ljava.lang.String;#5d888759". Obviously, it not a valid javascript array definition.
Your need to process your java array first. Add the following code to your jsp(above your javascript code):
<%
StringBuilder sb = new StringBuilder();
sb.append("[");
for(String name : names) {
sb.append("'");
sb.append(name);
sb.append("',");
}
if(sb.charAt(sb.length() - 1) == ',') {
sb.setLength(sb.length() - 1); //remove tailing ','
}
sb.append("]");
String strNames = sb.toString();
%>
And then modify your js code to:
var names="<%=strNames%>";
After jsp rendered, your js code will be like:
var names="['foo','bar']";
which is a valid array definition in js. Then it will work.
If the data type of names in java is List<String>, the solution is similar.
I have found the answer.Thnx for the help
this is the answer
function validation() {
var x=document.getElementById("user").value;
var y=document.getElementById("user");
var z=document.getElementById("pass");
var names="<%=names%>";
names= names.replace("[", "").replace("]", "");
names=names.split(", ");
for (var j=0; j<names.length; j++) {
if (names[j].localeCompare(x)==0) {
return true;
}
z.removeAttribute("readonly", 0);
}
alert("You username is not registered on our databsae");
y.focus();
}
check this out
CASE 1
var names='{id:1,key:"Apple"}'; // here names is string
names.key // will give you error
// so you need to parse it
//using the json2.js script:
var obj = JSON.parse(names);
obj.key // will give you Apple
var obj = jQuery.parseJSON(names)// in jquery
Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.
CASE 2
var names={id:1,key:"Apple"}; // here names is object
names.key // will give you Apple
REFERENCE
JSON = > https://github.com/douglascrockford/JSON-js
I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.