JavaScript JSON Parse Issue ($.getJSON) - javascript

I can't seem to get the following code to output anything to the screen. JavaScript is not my strong suit!
This is the JavaScript code calling a local file that outputs a list of rooms
$.getJSON('roomupdate.php?level=1&div=1&callback=json',function(res){
console.log(res.rooms.name[0]);
});
In the above I'm merely trying to see the name of the first room in the console. And this is the JSON output (Which I can confirm the script can see and load)
json(
{
"rooms":
[
{ "name" : "Bedroom" },
{ "name" : "Living Room" },
{ "name" : "Lounge" },
{ "name" : "Kitchen" }
]
})
Could anyone suggest what I am doing wrong? Even to view in the console?
Lastly, can you loop through the array?

Your JSON data contains an object rooms and this object actually contains an array [], So to access the data inside your array you need to put the index on rooms :
console.log(res.rooms[0].name);

Use callback=? rather than callback=json so that jQuery knows you are using JSONp and can choose it's own name for the callback function.
$.getJSON('roomupdate.php?level=1&div=1&callback=?',function(res){
//alert('Your name is '+res.rooms);
console.log(res.rooms.name[0]);
});
See http://api.jquery.com/jQuery.getJSON/#jsonp for details.
Edit:
Looking again, you will need to change the way you are accessing the data around. res.rooms.name[0] should be res.rooms[0].name because rooms is a list, and each room has a name property.

This will loop through the array of rooms and log the name of each one:
$.each( res.rooms, function( i, room ) {
console.log( room.name );
});
If that doesn't work, then add this statement at the beginning of your callback (where you have the console.log() call now):
debugger;
Load/run your page with the developer tools open, and it will stop in the debugger where you have that statement. Now you can look at all your variables in detail, try out expressions to see what they do, single step through your code, etc.

Related

Logic App bypass Null in filter query

I am building a Logic App that uses the Azure Resource connector to obtain a list of my resources. I would then like to filter the results to Microsoft.Compute resources that have a tag name and value of stop and normal.
Here is a snippet of resource that I receive back without any filters
{
"id": "/subscriptions/<subscription>/resourceGroups/Env1/providers/Microsoft.Compute/virtualMachines/MyVM1",
"name": "MyVM1",
"type": "Microsoft.Compute/virtualMachines",
"location": "westeurope",
"tags": {
"stop": "normal"
}
},
{
"id": "/subscriptions/<subscription>/resourceGroups/LogicApp/providers/Microsoft.Logic/workflows/DWSize-Check",
"name": "DWSize-Check",
"type": "Microsoft.Logic/workflows",
"location": "westeurope",
"tags": {}
}
As you can see, the bottom resource does not contain any tags, as with many others that will appear in the list
I use the standard Compose Filter Array connector to try and filter out from the value I receive back.
Here is the code that I wish to use for the filter command:
#and(contains(item()?['id'], '/Microsoft.Compute/virtualMachines/'), contains(item()?['tags'], variables('TagName')), contains(item()?['tags'], variables('TagValue')))
variables('TagName') and variables('TagValue') will be stop and normal, as show in the example tags listed in my results snippet.
However, because there is no tag values listed in other resources, such as Microsoft.Logic/workflows, I receive the following null error:
InvalidTemplate. The execution of template action 'Filter_array'
failed: The evaluation of 'query' action 'where' expression
'#contains(item()?['tags'], variables('TagValue'))' failed: 'The
template language function 'contains' expects its first argument
'collection' to be a dictionary (object), an array or a string. The
provided value is of type 'Null'.'.
Would anyone know how to get around this?
I have tried similar queries to this #contains(item().tags?.stop, variables('TagValue')) just to see if it picks up anything, but I'm still blocked by a null response :(
I tried the above with the help of the Workflow Definition Language, but still no dice. Any help would be greatly appreciated.
EDIT
In addition to the answer posted by Thomas, I have performed the following (image below) to filter out null from the results and get to the TagName, but I am still unable to get to the TagValue, even if I use contains:
#and(contains(item()?['tags'], variables('TagName')), contains(item()?['tags'], variables('TagValue')))
or event just trying to look for TagValue
#contains(item()?['tags'], variables('TagValue'))
You can check for null and return an empty value (an empty array in your case).
You can replace item()?['tags'] with this expression or create a variable :
if(equals(item()?['tags'], null), [], item()?['tags'])

JavaScript / JSON - Access array element using a key name as index

I want to be able to access an array element by using a unique key name instead of a numeric index. In my situation, I'm making a Discord bot and each servers have their own settings. When someone sends a message on a server, I want to access some of this server's settings (such as a message prefix). IMPORTANT: Right now, the only way I can do this is looping through all the servers that the bot is in, which in long-term, could slow it down if there's hundreds of active servers sending messages. So looping through all the servers is already being done right now, but I want a direct way without having to do this.
conf.json:
{
"Settings": [
"358262452343013386" {
"prefix": "$",
"Admins": [
"155444308395294720"
],
"NotificationChannel": "358772856282284033",
"robotpieces": []
}
]
}
What I want to be able to do in my bot.js:
console.log(conf.Settings[message.guild.id].prefix); // outputs the prefix
// message.guild.id is the id of the server, which in this case, would translate to this:
console.log(conf.Settings["358262452343013386"].prefix) // outputs '$'
Any ideas of how I can achieve a similar goal WITHOUT having to loop through all of the array?
EDIT:
I know the following JSON is invalid, but I want a solution which would give the same result.
Aside from the fact that the JSON you posted is invalid, you could store the server settings as an object rather than an array, and access is just like you are trying to:
{
"Settings": {
"358262452343013386": {
"prefix": "$",
"Admins": [
"155444308395294720"
],
"NotificationChannel": "358772856282284033",
"robotpieces": []
}
}
}

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

get JSON object javascript

I have the Student.groovy class that hasMany Note.groovy
Student Class extend to User.groovy
I have a JavaScript function that takes as a parameter a list of notes in JSON.
The code below works.
$.each(data,function(key, value) {
alert(value.note);
alert(value.semester)
});
But if I do alert(value.student); me is returned [object, object]
and when I put alert(value.student.toSource()); It's shown ({class: "project.Student", id: 1})
If I do alert(value.student.name); It's shown undefined
You're most likely not sending back the correct JSON format to access the student's name.
As of now with the examples you have given you can only access the class and id of a given student.
value.student.class //<-- project.student
value.student.id //<-- 1
To be able to access the student's name you would have to have an object like so:
{
class: "project.Student",
id: 1,
name: "Example name"
}
If you think you are actually sending everything you need from the server just do a little $(document.body).append(data); or console.log(data); on your getJSON success callback so you can see clearly what you have.
I wouldn't be surpized if value.name works by the way. Depends on your json structure.

Getting started with extJS

I don't get what I'm doing wrong.
I'm trying to populate a form from a JSON string from the server and it doesn't work. I get nothing at all back. I examine the object and it's undefined. I've been beating my head against the wall for 3 days now. I need a simple example that works and I'll build from there.
Here's the simple example that I've been trying to use:
var messages = new Ext.data.JsonStore({
url: '/user/' + user_id,
method: 'GET',
root: 'user',
fields: [
{name: 'user_id'},
{name: 'first_name'}
],
listeners: {
load: messagesLoaded
}
});
messages.load();
function messagesLoaded(messages) {
console.log(messages);
}
Here's my JSON string:
{"success":"true","user":{"user_id":"2","first_name":"Test","last_name":"Test","email":null,"password":null,"city_id":"6379","birth_date":"2009-06-09","gender":"F","created_on":"2009-06-01 17:21:07","updated_on":"2009-06-14 17:20:14","active":"Y","cuisine_id":null}}
I really don't see what I'm doing wrong, but my JSON string isn't loading. Thanks!
Ok so you're almost there, but one problem. The root ("user" in this case) has to be an array. Even if it's an array with only 1 object. Ext.data.JsonReader (the default reader for a Ext.data.JsonStore) only accepts an array of results.
So your javascript looks just fine, but the JSON object returned by the server needs to look more like this.
{
"success":"true",
"user": [{
"user_id":"2",
"first_name":"Test",
"last_name":"Test",
"email":null,
"password":null,
"city_id":"6379",
"birth_date":"2009-06-09",
"gender":"F",
"created_on":"2009-06-01 17:21:07",
"updated_on":"2009-06-14 17:20:14",
"active":"Y",
"cuisine_id":null
}]
}
One more thing, consoloe.logging your store object will produce something like [Object] in Firebug... not too useful. You should either console.dir it, or log your actual data instead.
One comment about loading your form, once you get past loading your JSON (even though this example does not show that). Make sure your form is actually rendered before trying to load it with data, e.g. if trying to use something like form.loadRecord. Otherwise you'll end up with an empty form and no errors.

Categories

Resources