How to parse JSON data from nested array in PHP - javascript

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

Related

How can I sort the postman arry data response?

My postman API is returning data without sorting for the dataset arry. Anyone please help me to write the code to sort it?
Or also can make it by using .find
{
"api_version": "0.1",
"time_stamp": 1661856020,
"providerid": 09099,
"start_timestamp": 1654041600,
"end_timestamp": 1654214400,
"value": 1440,
"fields": [
"time_stamp",
"bsp"
],
"dataset": [
[
"2022-06-02T00:00:00Z",
59
],
[
"2022-06-01T00:00:00Z",
58
]
]
}
Postman is just a debugging tool. It lets you call the API and conveniently inspect its responses by changing various parameters. If you want changed API response, you'll need to make changes to the API.
Second, isn't the dataset array already sorted? -59 is lower than -58, right?
Edit: Updating answer based on comments.
You can try to write a javascript code like this to sort the response.
var object = {
"api_version": "0.1",
"time_stamp": 1661856020,
"providerid": 09099,
"start_timestamp": 1654041600,
"end_timestamp": 1654214400,
"value": 1440,
"fields": [
"time_stamp",
"bsp"
],
"dataset": [
[
"2022-06-02T00:00:00Z",
59
],
[
"2022-06-01T00:00:00Z",
58
]
]
}
object.dataset.sort(function(a, b){return a[1] - b[1]});
console.log(object);

Javascript: Parse array of json objects within a string

I have an array of json object within a string:
[
{
"title": "Ham on Rye",
"alternativeTitles": [],
"secondaryYearSourceId": 0,
"sortTitle": "ham on rye",
"sizeOnDisk": 0,
"status": "released",
"overview": "A bizarre rite of passage at the local deli determines the fate of a generation of teenagers, leading some to escape their suburban town and dooming others to remain…",
"inCinemas": "2019-08-10T00:00:00Z",
"images": [
{
"coverType": "poster",
"url": "http://image.tmdb.org/t/p/original/px7iCT1SgsOOSAXaqHwP50o0jAI.jpg"
}
],
"downloaded": false,
"remotePoster": "http://image.tmdb.org/t/p/original/px7iCT1SgsOOSAXaqHwP50o0jAI.jpg",
"year": 2019,
"hasFile": false,
"profileId": 0,
"pathState": "dynamic",
"monitored": false,
"minimumAvailability": "tba",
"isAvailable": true,
"folderName": "",
"runtime": 0,
"tmdbId": 527176,
"titleSlug": "ham-on-rye-527176",
"genres": [],
"tags": [],
"added": "0001-01-01T00:00:00Z",
"ratings": {
"votes": 5,
"value": 6.9
},
"qualityProfileId": 0
}
]
When I try to parse my array of json objects, it always returns a string, so when I try to access it by:
let data = JSON.parse(JSON.stringify(jsonData));
console.log(data[0].title)
it returns a specific character like "[", as if it was a string.
Te problem is that you are stringifying something that is already a JSON string.
Change this:
let data = JSON.parse(JSON.stringify(jsonData));
to this:
let data = JSON.parse(jsonData);

Sort internal array timestamps

I have an array with multiple elements that looks like this:
{
"name": "DR",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
]
],
"type": "areaspline"
},
{
"name": "SIT",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
],
[
"1506384000000",
3
],
[
"1534204800000",
1
],
[
"1531094400000",
1
],
[
"1528502400000",
1
]
],
"type": "areaspline"
},
This is the exact format I use to send data into high charts, however, the problem is that the chart breaks if the timestamps inside each environment (DR, SIT) are not in order.
How can I sort the 'data' inside each environment by timestamp?
This JSON is generated in PHP and sent through to JavaScript. So I would like to know how to sort the data inside either PHP or JavaScript.
Thanks.
This is actually rather trivial, once you know about the usort function. It allows you to define your own sorting function, so you can sort based on any factor of whatever the 2 objects it is passed.
Note that from your example json I had to add a set of square brackets around the whole thing to get PHP to parse it with json_decode .
<?php
// note I had to add square brackets to your
// demo json ....
$json='[{
"name": "DR",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
]
],
"type": "areaspline"
},
{
"name": "SIT",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
],
[
"1506384000000",
3
],
[
"1534204800000",
1
],
[
"1531094400000",
1
],
[
"1528502400000",
1
]
],
"type": "areaspline"
}]';
$json_obj_arr=json_decode($json,true);
print_r($json_obj_arr);
print("\n\n");
// a function to handle the sorting itself
// usort will pass it an array(timestamp,datavalue) for both
// $a and $b so we compare the [0] element of each
function cmp($a, $b)
{
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
}
// loop through the array, first is indexed
for($i=0;$i<count($json_obj_arr);$i++){
// then each one of those contains an
// associtive array with an element named ['data'] -
// this is an indexed array that you want sorted
// on the [0] element
usort($json_obj_arr[$i]['data'],"cmp");
}
print_r($json_obj_arr);
print("\n\n");
?>

If php string is in geojson array

I am trying to make a selection of country names via php, then do a check against my geojson to see if the country name I got from php matches any names in my json and if so, read the coordinates of it.
So basically I have ALL the countries in the geojson but only those that are found to match with my php variable get drawn with polygons.
The example is using leaflet, what if those countries where coloured only if my php variables with the country names matches?
I have a php string which i get like this:
$myCountry = get_field("country");
echo $myCountry;
String name result is Australia
This is the var_dump of get_field()
array(3) {
["country_name"]=>
string(9) "Australia"
["city_name"]=>
bool(false)
["state_name"]=>
bool(false)
}
I have a geojson like this
"type": "Feature",
"properties": {
"sovereignt": "Australia"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-77.53466, 23.75975],
[-77.78, 23.71],
[-78.03405, 24.28615],
[-78.40848, 24.57564],
[-78.19087, 25.2103],
[-77.89, 25.17],
[-77.54, 24.34],
[-77.53466, 23.75975]
]
],
[
[
[-77.82, 26.58],
[-78.91, 26.42],
[-78.98, 26.79],
[-78.51, 26.87],
[-77.85, 26.84],
[-77.82, 26.58]
]
],
[
[
[-77, 26.59],
[-77.17255, 25.87918],
[-77.35641, 26.00735],
[-77.34, 26.53],
[-77.78802, 26.92516],
[-77.79, 27.04],
[-77, 26.59]
]
]
]
}
},

Unable to access JSON response from AJAX API call

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

Categories

Resources