Data from geoJSON API call in Larvel 5.8 - laravel

I am trying to retrieve data from the weather.gov API - it returns the format in geoJSON and I am not sure how to actually get the data I want from it.
If I am using the weatherbit.io API, I have no issues as it returns JSON format in which I can pull from rather easily.
I am using GuzzleHTTP to make the API call.
I am playing around with learning APIs and I have an interest in weather so I figured I would work on an application in which I could pull information from the local weather station and output it in to readable format for users in a table.
The code I am currently using is:
$api_call = https://api.weather.xxx/points/LAT,LON;
$client = new \GuzzleHttp\Client();
$request = $client->get($api_call);
if ($request->getStatusCode() == 200) {
$weatherRequest = $request->getBody();
$requestedWeather = json_decode($weatherRequest);
$currentweather = $requestedWeather; ** THIS IS WHERE I NEED HELP ***
}
return $currentweather;
});
return view('currentweather', ["currentweather" => $currentweather]);
When I am returning $currentweather and var_dump it to the view, it gives me all the geoJSON data but I don't know how to correctly iterate through the data to pull the information I need.
When I pull from another API it gives a different JSON format which I can just pull like so:
$api_call = https://api.weatherbit.xx/v2.0/current?
$client = new \GuzzleHttp\Client();
$request = $client->get($api_call);
if ($request->getStatusCode() == 200) {
$weatherRequest = $request->getBody();
$requestedWeather = json_decode($weatherRequest);
$currentweather = $requestedWeather->data;
}
return $currentweather;
});
return view('currentweather', ["currentweather" => $currentweather]);
}
And when I use $currentweather in my view I can pull any data I need with the object string name. I am not sure how to pull the data when it's leading off with the #Context tag.
The data I want lies in the "properties" part of the geoJSON array and I just can't seem to figure out how to get that in the way I am currently using.
This is my geoJSON array return:
{ "#context": [ "https://raw.githubusercontent.xxx/geojson/geojson-ld/master/contexts/geojson-base.jsonld", { "wx": "https://api.weather.xxx/ontology#", "s": "https://schema.org/", "geo": "http://www.opengis.xxx/ont/geosparql#", "unit": "http://codes.wmo.xxx/common/unit/", "#vocab": "https://api.weather.xxx/ontology#", "geometry":
{ "#id": "s:GeoCoordinates", "#type": "geo:wktLiteral" }, "city": "s:addressLocality", "state": "s:addressRegion", "distance": { "#id": "s:Distance", "#type": "s:QuantitativeValue" }, "bearing": { "#type": "s:QuantitativeValue" }, "value": { "#id": "s:value" }, "unitCode":
{ "#id": "s:unitCode", "#type": "#id" }, "forecastOffice": { "#type": "#id" }, "forecastGridData": { "#type": "#id" }, "publicZone": { "#type": "#id" }, "county": { "#type": "#id" } } ], "id": "https://api.weather.xxx/points/xxx,xxx", "type": "Feature", "geometry": { "type": "Point", "coordinates": [ xxx, xxx ] }, "properties":
{ "#id": "https://api.weather.xxx/points/xxx,xxx", "#type": "wx:Point", "cwa": "xxx", "forecastOffice": "https://api.weather.xxx/offices/xxx", "gridX": 86, "gridY": 77, "forecast": "https://api.weather.xxx/gridpoints/xxx/xx,xx/forecast", "forecastHourly": "https://api.weather.xxx/gridpoints/xxx/xx,xx/forecast/hourly", "forecastGridData": "https://api.weather.xxx/gridpoints/xxx/xx,xx", "observationStations": "https://api.weather.xxx/gridpoints/xxx/xx,xx/stations", "relativeLocation":
{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [ xxx, xxx ] }, "properties": { "city": "xxx", "state": "xx", "distance": { "value": xxxx.xxxxxxxxx, "unitCode": "unit:m" }, "bearing": { "value": 150, "unitCode": "unit:degrees_true" } } }, "forecastZone": "https://api.weather.xxx/zones/forecast/xxxxxx", "county": "https://api.weather.xxx/zones/county/xxxxxx", "fireWeatherZone": "https://api.weather.xxx/zones/fire/SCZ050", "timeZone": "America/New_York", "radarStation": "xxxx" } }
Thanks for your help!

Any member of the JSON object can be accessed via the same name on the object returned by json_decode. Your weatherbit example $requestedWeather->data works because everything is in a member called data. So... $requestedWeather->properties will get you what you want from the weather.gov API.
You can also pass true as a second argument to json_decode to get back a plain PHP array instead.
$requestedWeather = json_decode($weatherRequest, true);
var_dump($requestedWeather['properties']);
This is often recommended because JSON allows member names that are not valid PHP object property names (e.g., names containing hyphens).

Related

Delete existing Records if they are not in sent array Rails 5 API

I need help on how to delete records that exist in the DB but not in array sent in a request;
My Array:
[
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
}
]
Below is my implementation: where am going wrong?
#topics = #course.topics.map{|m| m.id()}
#delete= #topics
puts #delete
if Topic.where.not('id IN(?)', #topics).any?
#topics.each do |topic|
topic.destroy
end
end
it's not clear to me where, in your code, you pick the ids sent in the array you showed before... so I'm assuming like this:
objects_sent = [
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
}
]
since you have your array like this, the only information you need to query on database is the ids (also, assuming the id's in the array are the id's on database, otherwise it wouldn't make sense). You can get them like this:
sent_ids = objects_sent.map{|o| o['id'].to_i}
Also, it seems to me that, for the code you showed, you want to destroy them based on a specific course. There would be 2 ways to do that. First, using the relationship (I prefer like this one):
#course.topics.where.not(id: sent_ids).destroy_all
Or you can do the query directly on the Topic model, but passing the course_id param:
Topic.where(course_id: #course.id).where.not(id: sent_ids).destroy_all
ActiveRecord is smart enough to mount that query correctly in both ways. Give it a test and see which works better for you

How to use JSONpath to extract specific values

I'm using JSONpath to try and find data with an array of JSON objects but I'm struggling to get to the information I want. The array contains many objects similar to below where there are values for RecID throughout. If I use $..RecID I get them all when I only want the first Key.RecID of each object (with a value 1338438 in this example). Is there a way to only extract the top level Key.RecID value?
BTW I'm trying to do this in jMeter and I'm assuming JSONpath is the best way to do what I want but if there is a better way I'd be happy to hear about it.
Thanks in advance
[{
"Key": {
"RecID": 1338438
},
"Users": [{
"FullName": "Miss Burns",
"Users": {
"Key": {
"Name": "Burns",
"RecID": 1317474
}
}
},
{
"FullName": "Mrs Fisher",
"Users": {
"Key": {
"Name": "Fisher",
"RecID": 1317904
}
}
}
],
"User": {
"FullName": "Mrs Fisher",
"Key": {
"Name": "Fisher",
"RecID": 1317904
}
},
"Organisation": {
"Key": {
"RecID": 1313881
}
}
}]

Laravel data recording with API

I save the received data from the API to the database. In my API result, there is the following answer:
"opponents": [
{
"opponent": {
"acronym": "RH",
"id": 127276,
"image_url": "/image/127276/reverse_heaven_logo_std.png",
"location": null,
"modified_at": "2020-04-14T19:03:48Z",
"name": "Reverse Heaven",
"slug": "reverse-heaven"
},
"type": "Team"
},
{
"opponent": {
"acronym": " neon",
"id": 2061,
"image_url": "/image/2061/neon_esport.png",
"location": "PH",
"modified_at": "2020-04-14T19:04:02Z",
"name": "Neon Esports",
"slug": "neon-esports"
},
"type": "Team"
}
],
If i use var_dump($opponents), i receive only last opponent from API. How can I save exactly 2 values that are in the array under the same name opponent->name?
Since you are using laravel, you may use collections.
$decoded = json_decode($opponents);
return collect($decoded->opponents)->pluck('opponent.name')->toArray();
you may do it in a single line if you prefer;
return collect(json_decode($opponents)->opponents)->pluck('opponent.name')->toArray();
first decode the json like this
$decoded_opponents = json_decode($opponents);
then create a empty array
$array = [];
run a foreach loop on you decoded data
foreach($decoded_opponents->opponents as $key=>$value){
$array[]=$value->opponent->name;
}
the names now stored in $array

Group array items with eloquent

I have the following eloquent query:
$extras = EventExtra::select('id', 'category', 'name', 'price', 'description', 'company')->get();
It gets some data from me from my database. What i want is for the returned data to be grouped twice, first by the category and then second by the company so that in the end i have something like this returned to the client:
[
{
"name": "donation",
"collection": [
{
"name": "sampleCompany1",
"array": [
{
"name": "extra1",
"description": "",
"value": ""
},
{
"name": "extra4",
"description": "",
"value": ""
},
{
"name": "extra6",
"description": "",
"value": ""
}
]
}
]
},
{
"name": "donation",
"collection": [
{
"name": "sampleCompany2",
"array": [
{
"name": "extra2",
"description": "",
"value": ""
},
{
"name": "extra3",
"description": "",
"value": ""
}
]
}
]
}]
I just typed the above myself so it might not be valid object array but basically it shows what i want to accomplish here.
You can use Collection to build your custom object. Something like this:
$return_data = Collect();
To add items in the collection with a property, you can use the put function.
$inner_data->put('name',$extras->name);
You can also add a collection within a collection.
To just push an existing collection in the collection, use push function
$inner_data->push($some_collection)
EDIT: Since you want a working example, see this below:
Lets say you want to create the following using collection:
{
"name": "extra1"
"description": "",
"value": ""
}
You will do something like this:
$my_collection = Collect();
$my_collection->put('name','extra1');
$my_collection->put('description','');
$my_collection->put('value','');
Now you can add this collection to another collection where you don't need a key. So lets say now it looks like this:
[
{
"name": "extra1"
"description": "",
"value": ""
},
{
"name": "extra4"
"description": "",
"value": ""
}
]
You will now do:
$my_final_collection = Collect();
foreach($my_collections as $my_collection) {
$my_final_collection->push($my_collection); // and so on in a loop
}

json deserializing coming back empty

I took suggestions from here and tried to create a class with objects for the parts I need to parse from my json feed. I then tried to deserialize it before mapping the field contents to my objects but the deserialization returns nothing.
Here is the json feed content:
"data": [
{
"id": "17xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxx",
"from": {
"name": "Lxxxxxx",
"category": "Sports league",
"id": "17xxxxxxxxxxxxx"
},
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQB4GscSy-2RHY_0&w=130&h=130&url=http\u00253A\u00252F\u00252Fwww.ligabbva.com\u00252Fquiz\u00252Farchivos\u00252Fbenzema-quiz-facebook.png",
"link": "http://www.xxxxxva.com/quiz/index.php?qid=34",
"source": "http://www.lxxxxva.com/modulos/redirectQuiz.php?name=benzema&q=34&time=1312827103",
"name": "DEMUESTRA CU\u00c1NTO SABES SOBRE... BENZEMA",
"caption": "www.xxxxxva.com",
"description": "Demuestra cu\u00e1nto sabes sobre Karim Benzema, delantero del Real Madrid.",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yj/r/v2OnaTyTQZE.gif",
"type": "video",
"created_time": "2011-08-08T18:11:54+0000",
"updated_time": "2011-08-08T18:11:54+0000",
"likes": {
"data": [
{
"name": "Jhona Arancibia",
"id": "100000851276736"
},
{
"name": "Luis To\u00f1o",
"id": "100000735350531"
},
{
"name": "Manuel Raul Guerrero Cumbicos",
"id": "100001485973224"
},
{
"name": "Emmanuel Gutierrez",
"id": "100000995038988"
}
],
"count": 127
},
"comments": {
"count": 33
}
},
{
"id": "17xxxxxxxxxxxxxxxx_xxxxxxxxxxxxx",
"from": {
"name"
and here is the code I am trying. I tried to also use the jsontextreader and loop through each tokentype and check each one and then read the value but this looks like it will turn out to be tedious.
....
//fetch the content
responsedata = reader.readtoend()
......
dim pp as facedata = JsonConvert.DeserializeObject(of faceData)(responsedata)
console.writeline(pp.id.tostring)
and the class objects
Public Class faceData
Public Property id() as string
Get
Return f_id
End Get
Set(ByVal value as string)
f_id =value
End Set
End Property
Private f_id as string
......
any response appreciated.
Does anyone have links to full code where it actually works using vb.net.

Resources