I just need a little help with json and php. How do i echo certian parts of data if my request comes back looking like this:
{ "data": { "current_condition": [ {"cloudcover": "2", "humidity": "54", "observation_time": "09:05 PM", "precipMM": "0.0", "pressure": "1019", "temp_C": "11", "visibility": "10", "weatherCode": "113", "weatherDesc": [ {"value": "Clear" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png" } ], "winddir16Point": "N", "winddirDegree": "350", "windspeedKmph": "15", "windspeedMiles": "9" } ], "request": [ {"query": "48.85,2.35", "type": "LatLon" } ] }}
I am using a weather API, my code currently looks like:
$weather_url = file_get_contents("http://free.worldweatheronline.com/feed/weather.ashx?q=xxxxx&format=json&num_of_days=2&key=xxxxxxxxxxxxxxxxxx");
$json_output_w = json_decode($weather_url, true);
the q in the url string can be a zipcode, lat and long, or a city, i know it is returning data because i can dump the variable $json_output_w; but i just need a little guidance as how to actually echo certain parts of the data that is returned. like say i wanted to echo
windspeedMiles
The json_decode() function will return either an object or array (depending on the second argument). You can explore the structure of the returned item using the var_dump() function:
var_dump( $json_output_w );
From here you would discover what type of structure you need to consider when pulling values out. To get the windSpeedMiles value, you'd do the following:
echo $json_output_w["data"]["current_condition"][0]["windspeedMiles"];
Online Demo: http://codepad.org/BfhHbQMz
Related
I am getting json array after getting applying query logic.
[
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-20"
},
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "CRP",
"booking_date": "2018-05-20"
},
{
"id": "4",
"diag_name": "Seepz Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-21"
}
]
But i want a more justified json array written below.
[
{
"diag_name": "LT Diagnostics",
"test_name": [
{
"id": "3",
"name" : "Alk PO4"
},
{
"id": "3",
"name" : "CRP"
}
],
"booking_date": "2018-05-20"
},
{
"diag_name": "Seepz Diagnostics",
"test_name": [
{
"id": "4",
"name" : "Alk PO4"
}
],
"booking_date": "2018-05-21"
},
]
I am not getting it,How to do in php. I want a more consolidate json format.
Have you tried changing your SQL query to group by diag_name and booking_date? That would be the first step I’d employ to get the outer data.
Formatting the data in the nested manner you’re after could be a function of whatever record serializer you’re using — does it support nested JSON as a return type, or only flat JSON as your example return value shows?
If the record set -> JSON serializer only ever returns flat data, the comments above are correct that you will have to write your own formatter to change the shape of the JSON yourself...
The accepted answer of this other question may be of help:
Create multi-level JSON with PHP and MySQL
I'm not a PHP guy but this is a typical scenario to use functional programming by means of the monad Map.
Looking online I've found this article that could help you.
Changing datasource output is not always (seldom indeed) a viable option.
Enjoy coding
I have a JSON string and i want to get the value.
$s='{
"subscriptionId" : "51c04a21d714fb3b37d7d5a7",
"originator" : "localhost",
"contextResponses" : [
{
"contextElement" : {
"attributes" : [
{
"name" : "temperature",
"type" : "centigrade",
"value" : "26.5"
}
],
"type" : "Room",
"isPattern" : "false",
"id" : "Room1"
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}';
Here is the code which I used but it didn't work.
$result = json_decode($s,TRUE); //decode json string
$b=$result ['contextResponses']['contextElement']['value']; //get the value????
echo $b;
ContextResponses contains a numerically indexed array (of only one item) and value property is more deeply nested than what you are trying to reference (it is within attributes array). This would appear to be what you need:
$b = $result['contextResponses'][0]['contextElement']['attributes'][0]['value'];
When reading a JSON-serialiazed data structure like that, you need to make sure and note every opening [ or { as they have significant meaning in regards to how you need to reference the items that follow it. You also may want to consider using something like var_dump($result) in your investigations, as this will show you the structure of the data after it has been deserialized, oftentimes making it easier to understand.
Also, proper indention when looking at something like this would help. Use something like http://jsonlint.com to copy/paste your JSON for easy reformatting. If you had your structure like the following, nesting levels become more readily apparent.
{
"subscriptionId": "51c04a21d714fb3b37d7d5a7",
"originator": "localhost",
"contextResponses": [
{
"contextElement": {
"attributes": [
{
"name": "temperature",
"type": "centigrade",
"value": "26.5"
}
],
"type": "Room",
"isPattern": "false",
"id": "Room1"
},
"statusCode": {
"code": "200",
"reasonPhrase": "OK"
}
}
]
}
I have read about json_encode but still lack the logic in using it for my needs on this particular JSON structure.
Assuming the JSON structure is as follows :
{
"_id": "23441324",
"api_rev": "1.0",
"type": "router",
"hostname": "something",
"lat": -31.805412,
"lon": -64.424677,
"aliases": [
{
"type": "olsr",
"alias": "104.201.0.29"
}
],
"site": "roof town hall",
"community": "Freifunk/Berlin",
"attributes": {
"firmware": {
"name": "meshkit",
"url": "http:k.net/"
}
}
}
Some of the values of the attributes will be taken from the database while some are going to be hardcoded(static) like "type","api_rev". I was thinking of just using concatenation to build the structure but learnt its a bad idea. So if i am to use json_encode how may i be able to handle this structure ? array dimensions etc.
My PHP code:
$obj = json_decode($data);
print $obj->{'name'};
While it works for non-arrays, I can't for the life of me figure out how to print all the values within the "Reviews" Array.
What I would like to do is to loop through this response, probably with forreach(), resulting in a list containing the rating and excerpt for each review in the response.
Any guidance / direction is greatly appreciated..
Below is the JSON I'm working with. (it is the response from the Yelp API).
{
"is_claimed": true,
"rating": 4.5,
"mobile_url": "http://m.yelp.com/biz/economy-paint-and-collision-riverside",
"rating_img_url": "http://s3-media2.ak.yelpcdn.com/assets/2/www/img/99493c12711e/ico/stars/v1/stars_4_half.png",
"review_count": 19,
"name": "Economy Paint & Collision",
"snippet_image_url": "http://s3-media3.ak.yelpcdn.com/photo/ZOzoahw0Go_DEPLvxCaP_Q/ms.jpg",
"rating_img_url_small": "http://s3-media2.ak.yelpcdn.com/assets/2/www/img/a5221e66bc70/ico/stars/v1/stars_small_4_half.png",
"url": "http://www.yelp.com/biz/economy-paint-and-collision-riverside",
"reviews": [
{
"rating": 3,
"excerpt": "The Good:\nDennis quoted me a price over the phone about 1 month before I took my wifes 2010 Escalade in for repairs and when I took it in he gave me the...",
"time_created": 1357010247,
"rating_image_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/34bc8086841c/ico/stars/v1/stars_3.png",
"rating_image_small_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/902abeed0983/ico/stars/v1/stars_small_3.png",
"user": {
"image_url": "http://s3-media3.ak.yelpcdn.com/photo/mIsU7ugYd88lLA-XL2q1Cg/ms.jpg",
"id": "V9MDZvEBv-tBTF4YIoc7mg",
"name": "Sydney H."
},
"rating_image_large_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/e8b5b79d37ed/ico/stars/v1/stars_large_3.png",
"id": "HfOhzLIlJoUKSKU8euclqA"
},
{
"rating": 5,
"excerpt": "Dennis and his team did an amazing job on the roof of my fiancee's 2002 Acura RSX after years of living by the beach in San Francisco had mostly rusted...",
"time_created": 1354741952,
"rating_image_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png",
"rating_image_small_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png",
"user": {
"image_url": "http://s3-media3.ak.yelpcdn.com/photo/ZOzoahw0Go_DEPLvxCaP_Q/ms.jpg",
"id": "kOqCnCjYn0EbAhtH1tfjcw",
"name": "Jason H."
},
"rating_image_large_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png",
"id": "YzZg1LX6zeRaurq9tYUcMw"
},
{
"rating": 5,
"excerpt": "It's been a year since I had my car painted here, and I gotta say: It still looks just as good as it did when I first picked it up. You would never know...",
"time_created": 1361043626,
"rating_image_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png",
"rating_image_small_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png",
"user": {
"image_url": "http://s3-media1.ak.yelpcdn.com/photo/58coTtu1x5riHSgFEAQsfw/ms.jpg",
"id": "kVrW3138d5VL-AZ97wFF4A",
"name": "Jeanne M."
},
"rating_image_large_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png",
"id": "r5WtlQVMXiIMBR6S3N7RZw"
}
],
"phone": "9517870227",
"snippet_text": "Dennis and his team did an amazing job on the roof of my fiancee's 2002 Acura RSX after years of living by the beach in San Francisco had mostly rusted...",
"image_url": "http://s3-media3.ak.yelpcdn.com/bphoto/kodoEcmgHRG61pPaWRndbw/ms.jpg",
"categories": [
[
"Body Shops",
"bodyshops"
],
[
"Auto Repair",
"autorepair"
]
],
"display_phone": "+1-951-787-0227",
"rating_img_url_large": "http://s3-media4.ak.yelpcdn.com/assets/2/www/img/9f83790ff7f6/ico/stars/v1/stars_large_4_half.png",
"id": "economy-paint-and-collision-riverside",
"is_closed": false,
"location": {
"city": "Riverside",
"display_address": [
"2548 Rubidoux Blvd",
"Riverside, CA 92509"
],
"geo_accuracy": 8,
"postal_code": "92509",
"country_code": "US",
"address": [
"2548 Rubidoux Blvd"
],
"coordinate": {
"latitude": 34.0132437,
"longitude": -117.3923804
},
"state_code": "CA"
}
}
You are probably having trouble because reviews is an array and you are trying to access it as a JSON object.
$obj = json_decode($data, TRUE);
for($i=0; $i<count($obj['reviews']); $i++) {
echo "Rating is " . $obj['reviews'][$i]["rating"] . " and the excerpt is " . $obj['reviews'][$i]["excerpt"] . "<BR>";
}
I'm not sure what exactly you want but I guess you want print it just for debugging right now. You can try with print_r($obj); and var_dump($obj); - they must print something, especially var_dump().
When you see the data, you can easily edit function a little bit, so you can do for instance print_r($obj->reviews) or print_r($obj['reviews']), depending if $obj is object or array.
You can use var_dump or print_r.
<?php
$decodedJSON = json_decode($jsonData);
// Put everyting to the screen with var_dump;
var_dump($decodedJSON);
// With print_r ( useful for arrays );
print_r($decodedJSON);
// List just review ratings with foreach;
foreach($decodedJSON['reviews'] as $review){
echo $review['rating'];
}
?>
Here using objects example (to read reviews...raiting):
$jsonObject = json_decode($data);
foreach ($jsonObject->reviews as $data) {
echo $data->rating;
}
I m getting the below return from ajax call but not able to traverse it please please help.
{
"1": {
"tel1": null,
"status": "1",
"fax": "",
"tel2": null,
"name": "sh_sup1",
"country": "Anguilla",
"creation_time": "2010-06-02 14:09:40",
"created_by": "0",
"Id": "85",
"fk_location_id": "3893",
"address": "Noida",
"email": "sh_sup1#shell.com",
"website_url": "http://www.noida.in",
"srk_main_id": "0"
},
"0": {
"tel1": "Ahemdabad",
"status": "1",
"fax": "",
"tel2": "Gujrat",
"name": "Bharat Petro",
"country": "India",
"creation_time": "2010-05-31 15:36:53",
"created_by": "0",
"Id": "82",
"fk_location_id": "3874",
"address": "THIS is test address",
"email": "bp#india.com",
"website_url": "http://www.bp.com",
"srk_main_id": "0"
},
"count": 2
}
You can do it very easily:
for(i = 0; i < msg.count; i++) {
alert(msg[i]['name']);
}
But the structure of your JSON object is not that good for several reasons:
It does not reflect the structure of the actual data
With this I mean, that you actually have an array of objects. But in your JSON object the elements of the array are represented as properties of an object.
You have invalid JavaScript object property names.
Properties for objects in JavaScript are not allowed to start with numbers. But with msg = { "1": {...}} you have a number as property.
Fortunately it is not that bad because you can access this property with "array like" access msg["1"] (instead of the "normal way", msg.1). But I would consider this as bad practice and avoid this as much as possible.
Hence, as Matthew already proposes, it would be better to remove the count entry from the array on the server side, before you sent it to the client. I.e. you should get a JSON array:
[{
"tel1": "Ahemdabad",
"status": "1",
// etc.
},
{
"tel1": null,
"status": "1",
// etc.
}]
You don't need count as you can get the length of the array with msg.length and you can traverse the array with:
for(var i in msg) {
alert(msg[i].name);
}