I am unable to access and append the response from a AJAX call to the factual API.
I am receiving undefined errors however I try and structure the code accessing and iterating over the response.
I have managed to successfully log the data to console, now just need to add to the HTML on a page.
Below is the current code and API response structure, what I do not understand is when to use data and what exactly this relates to? Is this a keyword for any data received from a request or specific to certain API structures.
CODE:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
console.log('dom ready');
$("#search").on("click", runTing);
function runTing () {
var url = "http://api.v3.factual.com/t/places?q=Aldi,London&filters={%22country%22:%22GB%22}&KEY=111111111111111111111111";
$.ajax({
url: url,
dataType: "JSON",
success: function (data) {
var $latitude = $("<p>").text(response.data[0].address);
$('#info').append("$latitude");
}
});
};
});
</script>
</head>
<body>
<div id="info"></div>
</body>
JSON Response:
{
"version":3,
"status":"ok",
"response":{
"data":[
{
"address":"632-640 Kingsbury Rd",
"admin_region":"England",
"category_ids":[
171
],
"category_labels":[
[
"Retail",
"Supermarkets and Groceries"
]
],
"country":"gb",
"factual_id":"75fda75e-41a7-4645-b47a-9af5364fead1",
"hours":{
"monday":[
[
"8:00",
"21:00"
]
],
"tuesday":[
[
"8:00",
"21:00"
]
],
"wednesday":[
[
"8:00",
"21:00"
]
],
"thursday":[
[
"8:00",
"21:00"
]
],
"friday":[
[
"8:00",
"21:00"
]
],
"saturday":[
[
"8:00",
"21:00"
]
],
"sunday":[
[
"10:00",
"16:00"
]
]
},
"hours_display":"Mon-Sat 8:00 AM-9:00 PM; Sun 10:00 AM-4:00 PM",
"latitude":51.584985,
"locality":"London",
"longitude":-0.279941,
"name":"Aldi",
"neighborhood":[
"Kingsbury",
"Queensbury"
],
"post_town":"London",
"postcode":"NW9 9HN",
"region":"Greater London",
"tel":"0844 406 8800",
"website":"http://www.aldi.co.uk/"
},
{
"address":"1-4 London Rd",
"admin_region":"England",
"category_ids":[
171
],
"category_labels":[
[
"Retail",
"Supermarkets and Groceries"
]
],
"country":"gb",
"factual_id":"7edfabf8-3f28-4ee4-9322-6a296ed09a59",
"hours":{
"monday":[
[
"8:00",
"20:00"
]
],
"tuesday":[
[
"8:00",
"20:00"
]
],
"wednesday":[
[
"8:00",
"20:00"
]
],
"thursday":[
[
"8:00",
"20:00"
]
],
"friday":[
[
"8:00",
"20:00"
]
],
"saturday":[
[
"8:00",
"20:00"
]
],
"sunday":[
[
"10:00",
"16:00"
]
]
},
"hours_display":"Mon-Sat 8:00 AM-8:00 PM; Sun 10:00 AM-4:00 PM",
"latitude":50.829975,
"locality":"Brighton",
"longitude":-0.136322,
"name":"Aldi",
"neighborhood":[
"North Laines"
],
"post_town":"Brighton",
"postcode":"BN1 4JA",
"region":"East Sussex",
"tel":"0844 406 8800",
"website":"http://www.aldi.co.uk/"
},
response.data[0].address
supposed to be
data.response.data[0].address
The object that is returned from the BE, is currently in data (parameter for the callback).
So there is one more nested layer before you try accessing the response property.
Also as #chaarlietfl pointed out
$('#info').append("$latitude");
^ ^
---------------> Need to get rid of quotes
Related
My MongooseSchema (simplified):
_id: (ObjectId)
storage: [
{
location: String
storedFood:[
{
"name": String
"code": String
"weight": Number
}
]
}
]
I want to dec the weight, but not below 0. There is a stackoverflow answer that does this(The second answer from #rpatel). Great! The problem here is that he uses a update-pipeline WITHOUT nested documents. I didnt find a source where I could learn something about mongdob pipelines and nested object (If you have any please let me know, I really want to learn complex pipelines)
Is someone here who could adapt the following code to decrement weight,where location equals for example "Dubai" and code equals for example "38102371982" ?
Code from #rpatel:
Mongo-Playground
Example-Document:
{
"key": 1,
value: 30
}
db.collection.update({},
[
{
$set: {
"value": {
$max: [
0,
{
$subtract: [
"$value",
20
]
}
]
}
}
}
])
A ready playground.
One option is to use double $map with $cond in order to get into the double nested array item:
db.collection.update(
{storage: {$elemMatch: {location: wantedLoc}}},
[{$set: {
storage: {
$map: {
input: "$storage",
as: "st",
in: {$cond: [
{$eq: ["$$st.location", wantedLoc]},
{location: "$$st.location",
storedFood: {$map: {
input: "$$st.storedFood",
in: {$cond: [
{$eq: ["$$this.code", wantedCode]},
{$mergeObjects: [
"$$this",
{weight: {$max: [0, {$subtract: ["$$this.weight", reduceBy]}]}}
]},
"$$this"
]}
}
}
},
"$$st"
]}
}
}
}}]
)
See how it works on the playground example
I have a long list of coordinates (sent by a GPS sensor) that represent the movement of an asset.
I'm using leaflet to render the GeoJSON and it works fine if I render the LineString as a single feature, but if I break it down into multiple features (inside a FeatureCollection - to apply a different dynamic color) I start to see "holes" between features.
I'm pretty sure that this is due to the fact that there is actually a "hole" in the data I'm receiving. But why it works as a single LineString feature? Is there a way to fix this?
This is an extract of the GeoJSON (very large object)
there are 3 of the 866 features of the object
{
"type":"Feature",
"properties":{
"type":"traffic",
"color":"#ffa600"
},
"geometry":{
"type":"LineString",
"coordinates":[
[
7.583125,
45.0485616
],
[
7.5830532999999996,
45.0485816
],
[
7.58299,
45.0486133
],
[
7.582893299999999,
45.0486066
],
[
7.5828682999999995,
45.04859
]
]
}
},
link to bin
https://jsbin.com/nexijajake/edit?html,output
example with single feature
https://jsbin.com/guqihajalu/1/edit?html,output
Actually, there is nothing wrong with rendering. Your data array (in your jsbin link) is an array of linestrings that are not connected with each other. You got a schema like this (imagine each row is a linestring):
[pointA-pointB-pointC]
[pointD-pointE-pointF]
In order for your line to be continuous, the last point of each linestring should exist in the next linestring as first point:
[pointA-pointB-pointC]
[pointC-pointD-pointE-pointF]
This way, your line will be continuous.
For example, the following sample (taken from your jsbin) has a gap:
const data = [
{
"type":"Feature",
"properties":{
"type":"traffic",
"color":"#ffa600"
},
"geometry":{
"type":"LineString",
"coordinates":[
[
7.583125,
45.0485616
],
[
7.5830532999999996,
45.0485816
],
[
7.58299,
45.0486133
],
[
7.582893299999999,
45.0486066
],
[
7.5828682999999995,
45.04859
]
]
}
},
{
"type":"Feature",
"properties":{
"type":"normal",
"color":"#07e36a"
},
"geometry":{
"type":"LineString",
"coordinates":[
[
7.582795,
45.0485149
],
[
7.582624999999999,
45.0483233
],
[
7.581984899999999,
45.047521599999996
]
]
}
}
];
The gap is fixed (the first point of the second linestring is the last point of the first linestring):
const data = [
{
"type":"Feature",
"properties":{
"type":"traffic",
"color":"#ffa600"
},
"geometry":{
"type":"LineString",
"coordinates":[
[
7.583125,
45.0485616
],
[
7.5830532999999996,
45.0485816
],
[
7.58299,
45.0486133
],
[
7.582893299999999,
45.0486066
],
[
7.5828682999999995,
45.04859
]
]
}
},
{
"type":"Feature",
"properties":{
"type":"normal",
"color":"#07e36a"
},
"geometry":{
"type":"LineString",
"coordinates":[
//the first point here is the last of previous linestring
[
7.5828682999999995,
45.04859
],
[
7.582795,
45.0485149
],
[
7.582624999999999,
45.0483233
],
[
7.581984899999999,
45.047521599999996
]
]
}
}
];
How can I get access to the 'Roofing Insulation' array values in JS? Is it even possible with duplicate attribute names?
I have tried productListing['Roofing Insulation']['Roofing Insulation'] and many more types of syntax without success. I am aware the duplication is poor practice but it's all I have to work with...
{
"storeServices":{
"Local Services":[
"Rooftop",
"EPDM",
"Next-Day Delivery Available"
],
"National Services":[
"Covered",
"Window",
"Job Site Signs"
]
},
"productListing":{
"Roofing Insulation":{
"Roofing Insulation":[
"Celotex",
"Dow",
"Foamular",
"Johns Manville",
"Pactiv",
"Tyvek"
]
},
"Other Products":{
"Other Products":[
"Caulks/Sealants",
"Shutters",
"Tools & Equipment",
"Engineered Lumber",
"Roofing & Siding Accessories"
]
},
"Low Slope Roofing":{
"Low Slope Roofing":[
"Johns Manville",
"Mule-Hide Products",
"Versico"
]
},
"Steep Slope Roofing":{
"Concrete & Clay Roof Tiles":[
"Vande Hey Raleigh"
],
"Asphalt Shingles":[
"CertainTeed",
"GAF",
"Owens Corning"
]
},
"Windows & Doors":{
"Replacement Windows":[
"Pella"
],
"New Construction Windows":[
"Pella"
],
"Exterior Doors":[
"Pella"
],
"Skylights":[
"Velux"
]
},
"Siding":{
"Vinyl Siding":[
"Mastic Home Exteriors"
]
}
},
"branchDetails":{
"branchNumber":"1"
}
}
We can't help unless we see what you have tried and your code.
It should work if you do access it like below:
obj.productListing['Roofing Insulation']['Roofing Insulation']
Below is an example for you to showcase this:
var obj = {
"storeServices": {
"Local Services": [
"Rooftop",
"EPDM",
"Next-Day Delivery Available"
],
"National Services": [
"Covered",
"Window",
"Job Site Signs"
]
},
"productListing": {
"Roofing Insulation": {
"Roofing Insulation": [
"Celotex",
"Dow",
"Foamular",
"Johns Manville",
"Pactiv",
"Tyvek"
]
},
"Other Products": {
"Other Products": [
"Caulks/Sealants",
"Shutters",
"Tools & Equipment",
"Engineered Lumber",
"Roofing & Siding Accessories"
]
},
"Low Slope Roofing": {
"Low Slope Roofing": [
"Johns Manville",
"Mule-Hide Products",
"Versico"
]
},
"Steep Slope Roofing": {
"Concrete & Clay Roof Tiles": [
"Vande Hey Raleigh"
],
"Asphalt Shingles": [
"CertainTeed",
"GAF",
"Owens Corning"
]
},
"Windows & Doors": {
"Replacement Windows": [
"Pella"
],
"New Construction Windows": [
"Pella"
],
"Exterior Doors": [
"Pella"
],
"Skylights": [
"Velux"
]
},
"Siding": {
"Vinyl Siding": [
"Mastic Home Exteriors"
]
}
},
"branchDetails": {
"branchNumber": "1"
}
};
document.getElementById("demo").innerHTML = obj.productListing['Roofing Insulation']['Roofing Insulation'];
<p id="demo"></p>
I have layout builder in React to keep data structure and text I use ImmutableJS objects.
Such structure with attributes as text or css styles is saved into database as JSON.
To make it JSON I using json-immutable library: serialize, deserialize functions.
After save in database I provide configuration for react components as javascript variables. For example my backend generate js file with variables or small part is printing directly in html code using script tag.
Data are JSON or decoded javascript.
The biggest problem I have with save special chars.
For example if someone set ' single quote in some attribute it is saved directly.
But when I print it in html code as
var myConfig = '{anyjson}';
when inside JSON is single quote parser throw error. The same with double quotes, & (ampersant) or any chars used in html code like <,/>
Single quote I replace to \' when I print it in html code.
But I think does exists any way to save keep all data in JSON and still they will easy to decode by deserialize function to parse JSON to ImmutableJS objects.
Code example
https://jsfiddle.net/jaroapp/2yzud6ua/2/
var structure = {
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"Map",
"data":[
[
"html_el_qb7tyhi",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_qb7tyhi"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
"B&B is the best company. It's my hope for new markets."
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
[
"background-image",
"url(\"/path/to/image.jpg\")"
]
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_qb7tyhi"
]
]
}
],
[
"html_el_2dgupn7",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_2dgupn7"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"entityMap":{
},
"blocks":[
{
"key":"3ia22",
"text":"Text saved with html inside",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":[
],
"entityRanges":[
],
"data":{
}
}
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
null
],
[
"html",
"<p class=\"md-block-unstyled\">Text saved with html inside</p>"
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_2dgupn7"
]
]
}
]
]
}
],
[
"containersMap",
{
"__iterable":"Map",
"data":[
]
}
],
[
"componentsMap",
{
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
]
]
}
]
]
};
Such structure I set as parameter into ReactJS component.
If I set it as JSON and wrap in quotes then the browser throws an error. If I set it as JavaScript object into the React component I can't make ImmutableJS from this one, because this structure is read by this
https://www.npmjs.com/package/json-immutable library (I use the same to make JSON from Immutable JS to save it in database);
Thanks in advance for any hints.
I solved this problem. Short description, maybe will helpful for someone.
I get file with deserialize function form json-immutable package. And I modified function deserialize to
export function deserialize(json){
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if(typeof json==='string'){
return JSON.parse(json, function(key, value, options){
return revive(key, value, options);
});
}else{
return JSON.parse(JSON.stringify(json), function(key, value, options){
return revive(key, value, options);
});
}
}
Function in package use JSON.parse for param. Maybe it's not the most elegant solution but I don't have time to find way to don't "re-json" object. Standard Object.keys and map return origin object.
I am struggling to retrieve some values from a JSON file formatted like this:
{
"#context": [
"https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
{
"wx": "https://api.weather.gov/ontology#",
"#vocab": "https://api.weather.gov/ontology#"
}
],
"type": "FeatureCollection",
"features": [
{
"id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-95.45,
32.36
],
[
-96.07,
32.36
],
[
-96.08,
32.76
],
[
-95.92,
32.82
],
[
-95.85,
32.77
],
[
-95.77,
32.77
],
[
-95.76,
32.75
],
[
-95.71,
32.75
],
[
-95.66,
32.71
],
[
-95.64,
32.72
],
[
-95.59,
32.68
],
[
-95.6,
32.48
],
[
-95.47,
32.37
],
[
-95.45,
32.36
]
]
]
},
"properties": {
"#id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"#type": "wx:Alert",
"id": "NWS-IDP-PROD-2485131-2320093",
"areaDesc": "Van Zandt",
"geocode": {
"UGC": [
"TXC467"
],
"SAME": [
"048467"
]
},
"references": [],
"sent": "2017-08-13T00:03:41+00:00",
"effective": "2017-08-13T00:03:41+00:00",
"onset": "2017-08-13T00:03:00+00:00",
"expires": "2017-08-13T01:00:00+00:00",
"ends": "2017-08-13T01:00:00+00:00",
"status": "Actual",
"messageType": "Alert",
"category": "Met",
"severity": "Severe",
"certainty": "Observed",
"urgency": "Immediate",
"event": "Severe Thunderstorm Warning",
"sender": "NWS Fort Worth TX",
"headline": "Severe Thunderstorm Warning issued August 12 at 7:03PM CDT expiring August 12 at 8:00PM CDT by NWS Fort Worth TX",
"description": "The National Weather Service in Fort Worth has issued a\n\n* Severe Thunderstorm Warning for...\nVan Zandt County in north central Texas...\n\n* Until 800 PM CDT.\n\n* At 703 PM CDT, a severe thunderstorm was located near Wills Point,\nmoving east at 25 mph.\n\nHAZARD...65 mph wind gusts and quarter size hail.\n\nSOURCE...Radar indicated.\n\nIMPACT...Hail damage to vehicles is expected. Expect wind damage\nto roofs, siding, and trees.\n\n* This severe thunderstorm will be near,\nCanton around 710 PM CDT.\nEdgewood around 715 PM CDT.\nFruitvale around 725 PM CDT.\nGrand Saline around 735 PM CDT.\nVan around 750 PM CDT.\n\nThis includes Interstate 20 between mile markers 513 and 542.",
"instruction": "For your protection get inside a sturdy structure and stay away from\nwindows.\n\nContinuous cloud to ground lightning is occurring with this storm.\nMove indoors immediately. Lightning can kill.\n\nHeavy rainfall is occurring with this storm, and may lead to flash\nflooding. Do not drive your vehicle through flooded roadways.",
"response": "Shelter",
"parameters": {
"eventMotionDescription": [
"2017-08-13T00:03:00.000-05:00...storm...277DEG...23KT...32.62,-95.97"
],
"hailSize": [
"1.00"
],
"windGust": [
65
],
"tornadoDetection": [
"POSSIBLE"
],
"VTEC": [
"/O.NEW.KFWD.SV.W.0313.170813T0003Z-170813T0100Z/"
],
"EAS-ORG": [
"WXR"
],
"PIL": [
"FWDSVRFWD"
],
"BLOCKCHANNEL": [
"CMAS",
"EAS",
"NWEM"
],
"eventEndingTime": [
"2017-08-13T01:00:00Z"
]
}
}
},
I am trying to get the values from the keys under the "properties" key. What I am struggling with is does the array start with "properties" nested under #context or under "features"? I am not familiar with JSON data that uses # keys.
There are more values I need. But for starters, I am just using the event key nested under "features" -> "properties" where most of the keys for the values I need. I am not getting output from that.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($data, true); // decode the JSON feed
foreach($results as $result) {
dump($result); //this will dump the array
foreach($results['features'] as $data) {
dump($data['event']);
}
}
?>
-Thanks
EDIT: Added suggestion to code for json_decode
As others have stated, you need to pass true as a second param to json_decode if you want to the result to be an associative array.
The hierarchy is features/properties/event so you can look through the features and pull what you want out of the properties of each feature.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$results = json_decode($data, true); // decode the JSON feed
foreach($results['features'] as $currFeature)
{
$currEvent = $currFeature['properties']['event'];
echo $currEvent."\n";
}
Use json_decode($data, true). The true tells json_decode to return nested associative arrays instead of a object.
As BarNakedCoder said:
json_decode($data, true)
but you also need to replace
dump($data['event']
with:
dump($data[0]['event'])