How to load icon for specific weather condition? (AngularJS) - javascript

I'm working on a weather app as a personal project. I have the bases of the app done where I make a HTTP get request to the Yahoo Weather API and it returns the data I want.
However I'm stuck on the next step, getting icons to load with the current conditions.
I setup a JSON file in my "models" folder and it looks like this:
[
{
"code": 32,
"icon": "img/sunny.png",
"text": "Sunny"
},
{
"code": 26,
"icon": "img/cloudy.png",
"text": "Cloudy"
}
]
And here's my request for that in my main controller (Not sure if I'm doing it right).
$http.get('models/conditions.json')
.success(function(data) {
vm.condition = data;
}).error(function(err) {
console.log(err);
});
In the view I'm using a combination of the ng-if and ng-src directives to try to load the icons. Again, I don't I'm doing it right.
<img ng-if="main.place.item.conditons.code === main.conditions.code" ng-src="{{main.conditions.icon}}">
Any ideas on how I can get this to work? Am I on the right track? Thanks for any answers!

You said the JSON is being retrieved correctly, so the problem lies in the fact that you are trying to use an array as an object with the ng-src tag. You have {{main.conditions.icon}}, assuming conditions is the JSON you retrieved, you must specify an array index, however, you probably don't want to do this because you don't have a way of knowing what index is related to what weather code.
The solution to this can come in a couple different ways. For one, if possible, you can alter the JSON data to simply be an object in the form:
{
"32": {
"icon": ...,
"text": ...
},
"26": {
"icon": ...,
"text": ...
}
}
If you are able to do this, then you can use conditions as an object and do:
<img ng-src="{{main.conditions[main.place.item.conditions.code].icon}}">
Of course, this is assuming the conditions property in the "main.place.item" object isn't also an array, if so you will have to adjust even further. Also, I am assuming you made a typo as you had conditions spelled wrong in your question with the ng-if attribute.

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'])

Nested json data in Angular 2 - how to filter?

I'm new with Angular, Js etc, and have a problem with understanding how should work with nested data. For example:
I have four json files:
categories
subcategories
posts
comments
It's better to have 4 different files like above, or one like this:
{
"id_category":"1",
"name":"business",
"subcategories":{
"id":"1",
"name":"ecommerse",
"posts": {
"id": 1,
"title": "New post"
"comments": {
"id": 1,
"text": "text text text"
}
}
}
Of course it's only an example, but for that example I need to find comment by Id = 1 to get information about which post this comment is related to, which subcategory and category.
Now I have four different files, and services to get data from json files. I can get a specific comment by ID:
getComment(Id: number) {
return this.comments.find(
(comment) =>
comment.id === Id
);
}
ok, fine. But If I want to get information about post, subcategory, and main category for this comment? What should I do?
It depends on what the specific needs of your application are.
With this structure:
{
"id_category":"1",
"name":"business",
"subcategories":{
"id":"1",
"name":"ecommerse",
"posts": {
"id": 1,
"title": "New post"
"comments": {
"id": 1,
"text": "text text text"
}
}
}
You could iterate over Categories and display a list, then allow a user to select a single category, and assign that to var currentCategory.
You could then iterate over currentCategory.subcategories to allow the user to select a subcategory and assign that to var currentSubCategory. You would keep drilling down then into currentSubCategory.posts, allow the user to select a post, assign that to var currentPost and then iterate over that to display currentPost.comments.
If you're fetching from a database in order to allow the user to drill down into the data for display only, then something like this would work.
If you're maintaining data in JSON files, then I would look at something like JSON Server https://github.com/typicode/json-server
If you're building something more substantial and you have a database backend, make use of the database and don't try to recreate that functionality in your JSON, use JSON as a transport for the data, but don't try to replicate entire tables or complex data structures in your front end code, just fetch what you need as you need it, as that will make for a much more stable and scalable application, and will also make it easier for you do fetch and update data in small manageable chunks.
For mocking a data backend using JSON, consider json-server
https://www.npmjs.com/package/json-server

How Do I See the Output of Changes to JSON

Updated to try to be more clear given the comments (Thank you for comments)
I apologize in advance for this question. I may just not have the vocabulary to properly research it. If I have an array of objects called restaurants stored in my project, for example:
restaurants: [
{
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I then run a function to add a unique idea to all the objects in the array. The result of console.log(restaurants) is this:
{
"id": 3472,
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"id": 9987,
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I would now like to have this updated array of objects available to look at in my project, via the text editor, as a variable or restaurants.json file. How do I actually see the new modified json array and how do i save it so that i can work with it the same way i did this one above? I am currently doing this in the browser. I can see the results if i log it to the console but I need to be able to work with the new output. Thanks for taking the time to answer.
You can encode/decode JSON with JSON.stringify() and JSON.parse().
Aside from converting to/from JSON, you work with standard JS objects and arrays:
var array = JSON.parse(json_str);
array[0].address = "5th Avenue";
console.log(JSON.stringify(array));
Well, there's really not enough information in your question but I assume a few things:
You've loaded the json data from somewhere and it has been turned into a javascript object.
You've edited the object somehow and wish to convert it back to json and save the changes.
Assuming the above to be true, you just need to serialize the object back to json and submit it back to your server where you can save it in any manner you deem appropriate.
You can serialize the javascript object with JSON.stringify() (see https://stackoverflow.com/a/912247/4424504)
Add the serialized json to a hidden field on the form and submit it.
On the server when processing the form submission, grab the data from the hidden field and do with it what you wish.
Or get it back to the server any way you wish (ajax call, whatever) the key point is to serialize the object to a json string and save it
Hope that helps...

Parsing JSON data from a Website

I have quite a few questions since I'm relatively new at javascript. I started writing this application that lets the user get stock information from the yahoo finance web service and display it on the website. Sounds easy right? I thought so too but I'm having a hard time manipulating the data I'm getting back. Maybe someone can help me get this working. I feel like I'm really close at this point.
The user enters their stock of choice in the stockTextBox such as AAPL or GOOG. Then I set a script attribute with concatenation. Now the confirm() line is VERY odd. If I don't have that confirm in there the alert in the function myCallBack doesn't seem to execute. I can't explain this at all. Maybe I don't now something I should.
Now if I debug I can tell for a back that stock information is coming back from the website. First here is the code and then the JSON data. I would sincerely appreciate it if anyone could help me get this thing to work. I've been fiddling with it for a couple of hours now. THANK YOU! In other words, my question is how do I go about display data that I got from a web service onto my web page?
<form id="stockInput">
Stock Name: <input type="text" id="stockTextBox">
<input type="submit" id="submitButton" value="Submit">
</form>
</b>
<label id="stockLabel"></label>
<script>
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
//tried to put to an element and then read the element value down below through concatenation in the src...
//document.getElementById("stockLabel").innerHTML = textValue;
var script = document.createElement('script');
script.setAttribute('src',"http://finance.yahoo.com/webservice/v1/symbols/"+textValue+"/quote?format=json&callback=myCallBack");
document.body.appendChild(script);
confirm(); //ODD POINT...
}
function myCallBack(data)
{
alert("HEY" + data);
//What I thought I would do. This doesn't output the right info.
//for(key in data)
//{
//alert(data[key]);
//}
}
</script>
</body>
</html>
Now here is the JSON that I can see in the debugger via Firefox:
myCallBack({
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [{
"resource": {
"classname": "Quote",
"fields": {
"name": "Google Inc.",
"price": "1030.579956",
"symbol": "GOOG",
"ts": "1383249600",
"type": "equity",
"utctime": "2013-10-31T20:00:00+0000",
"volume": "1640035"
}
}
}
]
}
});
You are only seeing [object] because it's displaying the data type. You need to get object attributes to obtain the data. The JSON data is very accessible from javascript seeing as how JSON stands for JavaScript Object Notation.
It's very simple once you get started, as the data is basically comprised of objects with attributes and lists of objects. the variable data is your root object, and you can access everything below it easily.
I'll provide a few examples of how you would access certain things in the data:
the attribute "name":
alert(data.list.resources[0].resource.fields.name);
the attribute "classname":
alert(data.list.resources[0].resource.classname);
It's just a text representation of Javascript objects. "resources" is a list of objects, "list" is an object, "fields" is an object, and "price" is a key/value pair to store data.
Read more here: http://www.json.org/
http://www.w3schools.com/json/
If I misunderstood the question let me know, I took a shot at what I thought you meant.
Treat the JSON object like a regular Javascript object. For instance, if you wanted to display the company name and price:
function myCallBack(data)
{
alert("Name: " + data.list.resources[0].resource.fields.name);
alert("Price: " + data.list.resources[0].resource.fields.price);
}
To display the whole thing in raw form for debugging purposes, you can convert it back into a JSON-serialized string:
function myCallBack(data)
{
alert(JSON.stringify(data));
}
More about JSON: https://developer.mozilla.org/en-US/docs/JSON

result not coming with d3js?

After lot of help from stackoverflow folks,finally resolved my json and now its looking good.
luck.json--->
{
"PERFECT_JSON_object":
{
"51b59c1bbae1c":
[
{ "id": "parties", "float_1": "0.006" , "float_2": "0.9"},
{ "id": "royal-challenge", "float_1": "0.02" , "float_2": "0.333" },
{ "id": "star-speak","float_1": "0.02","float_2":"0.1" }
],
"51b59c1bbae3c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"},
{ "id": "star-speak","float_1": "0.02", "float_2": "0.009" }
],
"51b59c1bbae5c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"}
]
}
}
I have been trying to get my head around d3js with json,and I must say I have progressed quite a bit.But I am still not able to get the output with json data.
I went through these link`s but dint help.
https://github.com/mbostock/d3/wiki/Requests
d3.js & json - simple sample code?
Access / process (nested) objects, arrays or JSON
MyFIDDLE with json(no output,something wrong in here)
same fiddle with some static values( without Json)--
This is the result that I want.
I know that d3.json method requires json file to be on server.For temporary basis,as the json file is small can we include it directly in a variable in our d3 script??
I think I am messing up with json data in a wrong way.Can somebody help me with it
Yes, you can just add the JSON in a variable and run it this way. See here for the updated jsfiddle. You basically just add your JSON after var data =.

Categories

Resources