I've got a function that queries my database and gets a list of usernames-- I've pasted it below:
*dbQuery.jsp*
<%!
org.json.JSONArray dbQuery(String SQL_STRING)
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session1 = sessionFactory.openSession();
org.hibernate.Query query = session1.createQuery(SQL_STRING);
java.util.List list = query.list();
org.json.JSONArray jsonArray = new org.json.JSONArray(list);
// Actual contact insertion will happen at this step
session1.flush();
session1.close();
return jsonArray;
}
%>
I then try to parse through the list of users, but can't get it to work right. Here's what I'm doing:
var users = <%=dbQuery("FROM Users")%>;
alert("User= " + users[0].getAttribute('username'));
Why doesn't this work? What is the right syntax to parse through the objects/attributes in this JSON Array?
users[0].getAttribute('username')
will not work
try
users[0].username
Related
I'm trying to access data from a json but i can't... I have tried some explanations i found on the internet, but i guess there is something wrong on my code.
I'm getting data from a sql server database using the following code:
async function getLogin1(Operador, Senha) {
try {
let pool = await sql.connect(config);
let getLogin1 = await pool.request()
.input('input_parameter', sql.VarChar, Operador)
.input('input_parameter1', sql.VarChar, Senha)
.query("SELECT Codigo, Operador, Senha FROM Usuario where Operador = #input_parameter and Senha = #input_parameter1");
return getLogin1.recordsets;
}
catch (error) {
console.log(error);
}
}
So i get the recordsets here and put in a json:
router.route("/Login1").get((request, response) => {
console.log(request.body.operador);
console.log(request.body.senha);
Operador = request.body.operador;
Senha = request.body.senha;
dboperations.getLogin1(Operador, Senha).then(result => {
console.log(Operador, Senha);
response.json(result);
var json = JSON.stringify(result);
console.log(json);
})
})
On the console it shows the json:
[[{"Codigo":1,"Operador":"Username","Senha":"123456"}]]
I would like to get the individual data (codigo, operador and senha) to put in a individual string each one, but i cant access the data.
When I try like json[0] for example i get all the json (because my json has every info on the first position i guess), and when i try json.Codigo (for example) i get a "undefined" error.
What am i doing wrong and what the best way to solve?
And sorry for the low knowledge, this is my very first api.
(And yes, this is a login code and its not the best way to treat user data but its a very small system for intern use)
Your JSON "result" is:
[[{"Codigo":1,"Operador":"MASTER","Senha":"TERA0205"}]]
So it is an array of array containing one object with keys Codigo, Operador, Senha.
To get the value of the Codigo of that object you would likely need to
access it like
var CodigoVal = result[0][0].Codigo; // 1
var OperadorVal = result[0][0].Operador; // "MASTER"
Looks like json has nested array, if so json[0] will give inner array so you have to probably do like json[0][0].Codigo
[
[
{ "Codigo":1,
"Operador":"Username",
"Senha":"123456"
}
]
]
If we look at the JSON you posted above, we have an array which has an array with an object at its first index.
So to get access to that object you need to do:
const obj = json[0][0];
Now from obj you can extract Codigo, Operado and Senha like
const condigo = obg.Condigo;
const operado = obg.Operado;
const senha = obg.Senha;
You can also directly access them like
var codigo = json[0][0].Codigo;
var operador = json[0][0].Operador;
var senha = json[0][0].Senha;
json.Codigo doesnt work because your json has a array in it. Which has the object you are trying to get data from.
json[0] returns everything because that gives you the object from that array
so if you want Codigo try json[0][0].Codigo
I hope this helped you!
I have got very large model list in view and i would like to send the list back to controller using ajax query. I have tried to send the whole model list back but since the model is too large, it exceeds the json maxlength specified within web.config. The encode method works for smaller list though.
var jsonString = #Html.Raw(Json.Encode(Model.modelName_small));
Only way that i can vision it to work is but filtering the large model list into smaller list using javascript (similar to a 'Where' SQL statement). My script are as follows (razor):
<script type="text/javascript" language="javascript">
function functionName(input1_decimal) {
var smallerList = new Array();
#foreach (var item in Model.modelName)
{
//input1_decimal should be within a certain range
#:if (input1_decimal - 0.1 <= #item.Property1) && (#item.Property1 <= input1_decimal + 0.1)
{
#:smallerList.push("#item");
}
}
//convert smallerList to json and send it to controller
}
<script>
it seems quite straight forward but I just can not get it to work. Might be something quite trivial. I have also tried:
var smallerList= Model.modelName.Where(x => (input1_decimal - 0.1 <= x.Property1) && (x.Property1 <= input1_decimal + 0.1));
Similarly, i have also tried
var smallerList = Model.modelName.filter(function (item) {
return (input1_decimal - 0.1 <= item.Property1) && (item.Property1<= input1_decimal + 0.1)
});
Thank you for your patience. i hope i have explained it clearly as to what i am trying to achieve. I am not a developer. Programming just for fun and self education.
Are you modifying data on the view ? If so, one other approach is to post only modified data to the controller in order to minimized the json string length and retrieve the rest of the data directly in the controller.
instead of editing jsonmaxlength field within web.config, I assigned MaxJsonLength to Int32.MaxValue. Created a list and assigned properties to model properties and serialise into Json object list. Then i filtered the list using $.grep function. Finally, I was able to send objJsonSmallList back to controller... Happy days :)
#{
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue;
//Create a list and assigning all the properties of the model
var data = Model.model_Name.Select(x => new
{
propName1 = x.property1,
propName2 = x.property2,
...
propNameN = x.propertyN
});
//serialize collection of anonymous objects
string strArr = js.Serialize(data);
}
var objJsonBigList = JSON.parse('#strArr'.replace(/"/g, '"'));
//small Filtered list send to controller via Ajax
var objJsonSmallList = $.grep(objJsonBigList, function (n) {
return ((input1_decimal- 0.1 <= n.Prop) && (n.Prop <= input1_decimal + 0.1))
});
const userPhoneNumber = await transaction.one(pgp.as.format(`${pgp.helpers.update({
modifiedById: login.objectId,
modifiedTimestamp: now,
phoneNumber
}, columnSets.userPhoneNumbers.forUpdateById)} WHERE object_id = $/objectId/ AND removed = $/removed/ AND userId = $/userId/ RETURNING *`, { objectId, removed: false, userId }));
Right now I am doing this in my code. I want to be able to
Utilize column set
Use pgp.update method along with column set to generate SQL
However, I am not sure how to utilize query file here as well. How can I use query file so I can avoid using RAW SQL string in my javascript code?
Right now I can only think of doing query file like so
{statement:raw} WHERE object_id = $/objectId/ AND removed = $/removed/ AND userId = $/userId/ RETURNING *
But this feels abit hackish to inject partial raw statement.
First, you declare statically your ColumnSet, object according to the columns and the table that you use. For example:
const cs = new pgp.helpers.ColumnSet(['col1, col2', 'col3'], {table: 'my-table'});
When it is time to execute the query, you prepare your WHERE condition like this:
const where = pgp.as.format(' WHERE object_id = ${objectId} AND removed = ${removed} AND
userId = ${userId} RETURNING *', {objectId, removed, userId});
Then you can generate a complete UPDATE sql like this:
const updateSql = pgp.helpers.update(data, cs) + where;
Now you can execute that sql.
I am not sure how to utilize query file here
In your example there isn't much point in using an external query file, though you can, if you want, as explained further.
You can create the following file:
${update:raw} WHERE object_id = ${objectId} AND removed = ${removed} AND
userId = ${userId} RETURNING *
Then you load it like you would any other QueryFile:
const qf = new pgp.QueryFile(path, options);
And then you can generate a complete SQL query like this:
const updateSql = pgp.as.format(qf, {
update: pgp.helpers.update(data, cs),
objectId,
removed,
userId
});
I am having trouble getting data from the nested pointers in my array of pointers from a query. I have an array of pointers like so: [{"__type":"Pointer","className":"QuizData","objectId":"rmwJrV55c7"},{"__type":"Pointer","className":"QuizData","objectId":"2132q8i9np”}, etc…]
That QuizData class also has a column named “ad” which is a Pointer to the “Ads” class. I can get the QuizData in a query using the following include statements on my query like so:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include("quizAdArr”);
__quizAdQueueQuery.include(["quizAdArr.QuizData"]);
BUT Neither of these or both combined don’t work as when I try to get column data from the ad it’s always undefined:
__quizAdQueueQuery.include(["quizAdArr.QuizData.ad"]);
__quizAdQueueQuery.include(["quizAdArr.QuizData.Ads"]);
This is my return from that query, where the column data "mediaType" that I am trying to access is always undefined:
return __quizAdQueueQuery.first().then(function(__resultsObj)
{
__quizQueueObj = __resultsObj;
__userQuizQueueArr = __quizQueueObj.get("quizAdArr");
var __quiz;
var __ad;
var __seenAd;
var __lengthInt = __userQuizQueueArr.length;
var __mediaTypeStr = __request.params.mediaType;
var __matchedQuizzesArr = [];
for (var __i = 1; __i < __lengthInt; __i++)
{
__quiz = __userQuizQueueArr[__i];
// console.log('__quiz.get("name") = '+__quiz.get("name"));
__ad = __quiz.get("ad");
// console.log("__ad.id = "+__ad.id);
//THE MEDIA TYPE IS ALWAYS RETURNING UNDEFINED HERE!!!
console.log('__ad.get("mediaType") = '+__ad.get("mediaType")+', __mediaTypeStr = '+__mediaTypeStr);
if (__ad.get("mediaType") == __mediaTypeStr)
{
//put all matches in array to be sorted
__matchedQuizzesArr.push(__userQuizQueueArr[__i]);
console.log("__matchedQuizzesArr.length = "+__matchedQuizzesArr.length);
}
}
return __matchedQuizzesArr;
});
Thanks for any help you can give! I also posted this as a bug in the Parse/Facebook issue reporter but was redirected here, so if this is a bug I can reopen it: https://developers.facebook.com/bugs/923988310993165/
EDIT Here is the updated, working query with nested includes for clarity:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include('quizAdArr');
__quizAdQueueQuery.include('quizAdArr.ad');
This should work (you only need to list the column names):
query.include('quizAdArr.ad');
Here's why:
You're querying QuizAdQueue so you don't need to list that
The QuizAdQueue class has an array in quizAdArr so you include it: query.include('quizAdArr');
Each quizAdArr element is a QuizData with an ad so you include it: query.include('quizAdArr.ad');
The issue was that you were including QuizData which is the name of a class and not a column name
In Rails, I am querying the database to build a data object for highcharts.
Here is my method from my controller:
def build_data_for_chart
data_array = Array.new
#data_array_as_json = ''
#issues.each {
|issue|
# returns an array of KeyIssue objects for a given issue
given_issue_array = KeyIssues.where(issue: issue).all
a = Array.new
#loop through each element extracting the timedate and % and add to new array
given_issue_array.each {
|entry|
a.push([entry.datetime.utc.to_date, entry.percentage])
}
#build the hash for an individual issue
temp_hash = {:name => issue, :data => a, :animation => false}
#add the individual issue and all its data to a final array that contains all the issues.
data_array.push(temp_hash)
}
#data_array_as_json = data_array.to_json.html_safe
end
Now I am trying to pull it out in a script in my view.
--- script ---
var data = $.parseJSON(<%= #data_array_as_json %>);
--- script ---
When I print to console, I can see the objects and all their data. Also when I print to html the output looks correct:
"[{\"name\":\"ABORIGINAL & NATIVE TITLE ISSUES\",\"data\":[[\"1993-11-01\",32],[\"1994-06-01\",27],[\"1994-09-01\",33],[\"1995-06-01\",26],[\"1995-09-01\",24],[\"1996-01-01\",20],[\"1996-09-01\",27],[\"1997-01-01\",33],[\"1997-06-01\",36],[\"1997-09-01\",36],[\"1998-01-01\",37],[\"1998-05-01\",33],[\"1998-09-01\",31],[\"1999-05-01\",30],[\"1999-09-01\",28],[\"2000-01-01\",30],[\"2000-05-01\",31],[\"2000-09-01\",34],[\"2001-01-01\",32],[\"2001-06-01\",29],[\"2001-09-01\",28],[\"2002-02-01\",25],[\"2002-06-01\",27],[\"2002-10-01\",25],[\"2003-02-01\",24],[\"2003-06-01\",26],[\"2003-10-01\",27],[\"2004-02-01\",27],[\"2004-06-01\",26],[\"2005-06-01\",30],[\"2006-06-01\",27],[\"2007-06-01\",31],[\"2008-07-01\",29]],\"animation\":false}]"
But when I go to print the data variable it is null (obviously due to not being valid input). What am I messing up?
FYI..
I needed to wrap it in single quotes.. to make it work..
$.parseJSON(' <%= #data_array_as_json %> ');
You can try this:
<script type="text/javascript">
var data = <%== data_array.to_json %>
</script>