getting an element inside json object in angular - javascript

I have this json in my server:
{"user":"bla","password":"passbla"}
and in side my ts file I accessing it like that:
this.http.get('http://myserver.com/myjson.json').subscribe(data => {
alert(data.text()); });
I getting the json text in the alert box all OK.
But I need to access a certain element in this json(let's say the "user" element)
but this :
alert(data.user);
or
alert(data.json().user);
are all returning undefined if any...
How do I get a certain element value inside a json like this?

alert(data.json()[0].user)
is the way to access the element...

Related

Retrieve Firebase Object id

Im using the following loop to get data from a table which is working fine:
database.once("value", function(snapshot){
snapshot.forEach(snap => {
log.console(snap.val().about_me)
})
Its displaying the data to logs as expected, But i can't seem to get the object id?
I need to get the value 49GRZb8B31MUfpBN3zvHKOHCMOa2
I have tried:
snap.val().key;
This returns undefined
And have tried snap.val()[0];
which returns me everything in the object
snap is a DataSnapshot type object. You can see that it has a property called key. So, you need to reference that property directly on the DataSnapshot like this:
snap.key // correct
But not via the raw data object like this:
snap.val().key // incorrect, you have no child named 'key' in your data

I want to store changeable data within one column of my table row

So, I have a vue component called stats. Basically how its stored is it has a name for example: 'goals'. It fetches the row with the id/name of 'goals' from the database and the point is to access the info column within that to fetch specific data.
This is how the row would look
ID Name Info Created_at Updated_at
"1" "user" "{"goal": 1,"current":500}" "2019-04-28 03:54:44" "2019-04-28 03:54:46"
I want to be able to access the data within the Info column and display it accordingly. I can't seem how to get it working though within javascript.
This is how i call it
axios.get('/api/stats/user').then((res) => {this.test = res.data; console.log(this.test)});
and in the console i get the object i want but info looks like this:
info: "{"goal": 1000, "current":500}"
and I can't seem to be able to grab it by ['goal'] or this.test.info.goal which is what I want
First of all, create a resource file for yor model and create an accessor for your info/goal field.
You should use the resource files for each json response which contains models/collection of models.
This way you can modify what to display in your json response about each model.

Trouble Accessing JSON Data in a Javascript Function Within an Express/Jade Template

I'm kind of new at Express/Jade, so apologies if this is a dumb question.
I'm passing JSON data in to a Jade template, but, though the data is definitely there and usable elsewhere on the page, I can't seem to access it in a Javascript function within the same page.
The code in question looks like this:
script.
function populateData(value){
console.log("Value = " + value);
for(i = 0;i <= 3;i++){
console.log("i = " + i);
if(value==i){
console.log("school = " + mydata.sclist[i].sName);
$('#input_sid').val(mydata.sclist[i].sID);
$('#input_spc').val(mydata.sclist[i].sPostcode);
}
}
}
form#form_add_booking(name="addbooking",method="post",action="/addbooking")
table.formtable
tr
td
span
b School Name
td
select#input_sname(name="sname" onChange="populateData(this.value)")
option.
====== select ======
each school, i in mydata.sclist
option(value=i).
#{school.sName}
So, in the above code the SELECT list gets correctly populated with school names from the JSON, but, when the onChange attribute fires the Javascript function, I get an 'Uncaught ReferenceError that 'mydata' is not defined.
What am I missing please?
I assume mydata is passed to jade when rendering the page. The page is then returned from the server to the client (web browser) as rendered HTML. You can't then access mydata variable because it's used only on server-side to render the page. (Select is rendered on serve-side)
To be able to access the data the way you want, you'll have to render javascript variable in addition to your code above which can then be used on the client-side. (when select is changed)
const clientSideData = !{(JSON.stringify(mydata))};
Place this to very top of populateData (it converts JSON object to string) and then replace mydata references in the function with clientSideData. In this way you'll have access to the data even from client-side as you'll render javascript variable.

Javascript error in accessing JSON

In the following JSON how to access id and name
console.log($scope.mylist)
{"data":"{\"projects\":[{\"id\":\"3\",\"title\":\"MYCLOUD\",\"desc\":\"DESC\"}]}"}
I tried the following
console.log($scope.mylist.data) //undefined
console.log($scope.mylist["data"])//undefined
console.log($scope.mylist.projects)//undefined
console.log($scope.mylist["projects"]) //undefined
Your data property contains JSON, so you need to JSON.parse that too.
$scope.mylist.data.projects = JSON.parse($scope.mylist.data);
Then you should be able to access it with
$scope.mylist.data.projects[0].id //etc
Though there's an underlying problem of how you're getting/sending that JSON.

Xstream generated json response for List<Object>

I am using Xstream to generate JSON for my application.I want to use JSON for ajax support. When i try
xstream.alias(classAlias, jsonModel.getClass()); //Note classAlias="records"
responseStream.println(xstream.toXML(jsonModel));
where jsonModel is actually a List of entity objects.Entity class name is Person which is in "beans" package so full qualified name would be beans.Person. OK
Person class has properties like id,name,age etc.
Generated JSON is
{"records":[{"beans.Person":[{"id":21,"name":"Name21","username":"Username21","password":"password21","age":41,"sex":true},{"id":22,"name":"Name22","username":"Username22","password":"password22","age":42,"sex":true},{"id":23,"name":"Name23","username":"Username23","password":"password23","age":43,"sex":true},{"id":24,"name":"Name24","username":"Username24","password":"password24","age":44,"sex":true},{"id":25,"name":"Name25","username":"Username25","password":"password25","age":45,"sex":true},{"id":26,"name":"Name26","username":"Username26","password":"password26","age":46,"sex":true},{"id":27,"name":"Name27","username":"Username27","password":"password27","age":47,"sex":true},{"id":28,"name":"Name28","username":"Username28","password":"password28","age":48,"sex":true},{"id":29,"name":"Name29","username":"Username29","password":"password29","age":49,"sex":true},{"id":30,"name":"Name30","username":"Username30","password":"password30","age":50,"sex":true}]}]}
I used $.getJSON of jquery to get this response on button click event. I checked the status which is "success" every time so this is working well.Problem occurs when i try to access first records i.e. person's information like id,username etc.
I write statements in Javascript as
<script>
$(document).ready(function() {
$("input").click(function(){
$.getJSON("http://mylocalhost:8080/Paging/paging/records?page=3",function(data,status){
alert(status);
alert(data.records[0].beans.Person[0].id);
});
});
});
</script>
First alert works but second doesn't.
Then javascript stops working as it does whenever encounters an error.What i can guess is that in records array Person object is followed by package name.This could be the reason because browser may look for beans object in records array which is not there because beans.Person is a single, atomic name in this case as shown in above. But not sure?
If this is actually problem then how can i stop/control XStream to name an object's name as just classname(person) instead of package.classname(beans.person) as it is being named by default.
or If everything is OK in produced JSON object then why can't i see the expected result? Why simple second alert statement is not working.
I got the answer I was to use
alert(data.records[0]["beans.Person"][0].id);
instead of
alert(data.records[0].beans.Person[0].id);
A useful link
http://www.javascripttoolbox.com/bestpractices/#squarebracket

Categories

Resources