I am trying to get my website to get the json from the geocode farm api. I know how to contstruct the address where the api is but I don't know how to get the data back and parse and then display it in a javascript alert.
If you can help me do that, I will be very grateful.
Getting useful data out of the JSON response
Once you have a working URL that dumps the required JSON data, it's very easy. PHP offers built-in functions for processing and dealing with JSON data. In this case, you want to decode the JSON data into a usable format, such as an array or object.
Converting the JSON response to an array
To get it into an array, you can simply do:
$arr = json_decode(file_get_contents('http://example.com/foo.json'), 1);
Knowing the structure of the array
Now in order to work with the array, you will have to know how it is structured. For that purpose, you can use the debugging function print_r():
echo '<pre>' . print_r($arr, 1) . '</pre>';
Traversing the array to extract information
Once you know the structure of the JSON data, you can traverse it using a foreach loop:
foreach ($arr as $key => $value) {
// Do more stuff with $value
}
You can make a request with PHP, for example using file_get_contents() and then echo the result into JavaScript. You can then use JavaScript to extract the information you need and generate an alert.
Simplified example:
<?php
$url = 'http://api-url...';
$response = file_get_contents($url);
$data = json_decode($response, true);
$coordinates = $data['geocoding_results']['COORDINATES'];
?>
<script>
var coordinates = <?php echo json_encode($coordinates); ?>;
alert(coordinates.latitude + '; coordinates.longitude);
</script>
Related
I want to decode json file resulted from DuckDuckGo API into a readeble html or PHP string.
I try with PHP json_decode, but nothing:
$object = json_decode($string, true);
echo $object['RelatedTopics']['Result'];
Any ideas?
From the JSON responde you posted, it is possible to see that RelatedTopics is an array. So you must first access an element of this array to then access the Result key:
echo $object['RelatedTopics'][0]['Result'];
Or in a loop just to test:
foreach ($object['RelatedTopics'] as $rel)
echo $rel['Result'];
I have some issue with a decoded Json object sended to a php file. I have tried some different format like this
{"2":"{Costo=13, ID=9, Durata_m=25, Descrizione=Servizio 9}","1":"{Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}"}
or this.
[{"Costo":"7.5","ID":"3","Durata_m":"30","Descrizione":"Barba Rasoio"},{"Costo":"4.5","ID":"4","Durata_m":"20","Descrizione":"Barba Macchinetta"}]
In order the first, any suggestions helps me, then i have converted previous string using GSON, however php doesn't decode.
This is my php:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data['servizi'] as $key => $value)
{ echo "Key: $key; Value: $value<br />\n";
}
How can I access single elements of array? What I'm doing wrong? Thanks in advance
I think you should check the content in this way
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
echo "FROM PHP: " . $value;
echo "Test : " .$value['ID'];
}
your elements of {Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}
are not properly formated as an array element. That is a pure string and not an array value.
This is a json object with 1 element of array:
{
"1": {
"Costo": 7,
"ID": 8,
"Durata_m": 20
}
}
The Inside are json objects. Therefore your json string was not properly formated to operate with that logic. What you had was an element of a string. That is the reason why it was a valid json (passing jsonlint) but was not the correct one that you wanted to use.
UPDATE
Because this format is fix, I have a non-elegant way:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
//to separate each element
$newArray = explode(',',$value);
$newItem = explode('=', $newArray[1]);
echo "ID". $newItem[1];
}
That would be the dirty way to do it ONLY IF THE PLACEMENT OF DATA IS FIX. (ie the second element of the first explode is always ID.
I will leave it to someone else to make the suggested code better. I would recommend more to ensure that the json you are receive is proper because as I explained, it is incorrectly formated and as an api developer, you want an adaptive way for any given client to use the data efficiently.
I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];
I'm relatively new to JSON decoding, but I've been able to do it using this format (see below) for my looping and it doesn't seem to work for the desk.com api. Not sure if it's because the complexity of the JSON response doesn't like my formatting, or there is a better way to get the key->value pairs.
Here is the JSON response for this API call (http://dev.desk.com/API/topics/#list):
{"total_entries":4,"_links":{"self":{"href":"/api/v2/topics?page=1&per_page=50","class":"page"},"first":{"href":"/api/v2/topics?page=1&per_page=50","class":"page"},"last":{"href":"/api/v2/topics?page=1&per_page=50","class":"page"},"previous":null,"next":null},"_embedded":{"entries":[{"name":"Privacy & Security","description":"Information about your privacy.","position":1,"allow_questions":false,"in_support_center":true,"created_at":"2013-02-10T04:40:05Z","updated_at":"2013-09-26T00:12:13Z","_links":{"self":{"href":"/api/v2/topics/445877","class":"topic"},"articles":{"href":"/api/v2/topics/445877/articles","class":"article"},"translations":{"href":"/api/v2/topics/445877/translations","class":"topic_translation"}}},{"name":"Canned Responses","description":"Internal responses to common questions","position":3,"allow_questions":true,"in_support_center":false,"created_at":"2013-02-10T04:40:05Z","updated_at":"2013-09-26T00:31:25Z","_links":{"self":{"href":"/api/v2/topics/445878","class":"topic"},"articles":{"href":"/api/v2/topics/445878/articles","class":"article"},"translations":{"href":"/api/v2/topics/445878/translations","class":"topic_translation"}}},{"name":"FAQ","description":"Frequently Asked Questions","position":2,"allow_questions":false,"in_support_center":true,"created_at":"2013-02-10T04:40:05Z","updated_at":"2013-10-15T00:47:09Z","_links":{"self":{"href":"/api/v2/topics/445879","class":"topic"},"articles":{"href":"/api/v2/topics/445879/articles","class":"article"},"translations":{"href":"/api/v2/topics/445879/translations","class":"topic_translation"}}},{"name":"Suggestions & Feedback","description":"","position":4,"allow_questions":true,"in_support_center":true,"created_at":"2013-07-03T05:27:56Z","updated_at":"2013-10-16T02:38:11Z","_links":{"self":{"href":"/api/v2/topics/538220","class":"topic"},"articles":{"href":"/api/v2/topics/538220/articles","class":"article"},"translations":{"href":"/api/v2/topics/538220/translations","class":"topic_translation"}}}]}}
Here is how I was decoding and looping through to get to the NAME value:
$topics = json_decode($response);
foreach ($topics as $topic) {
echo "Name: " . $topic->_embedded->entries->name;
}
Thank you for the help.
Here you go:
$entries = $topics->_embedded->entries; // 'entries' from the json response is an array.
$i = 0;
while(isset($entries[$i])) { // Loop through the array to pick up all the data you need
$data[$i][0] = $entries[$i]->name;
$data[$i][1] = $entries[$i]->description;
$data[$i][2] = $entries[$i]->_links->self->href;
$i++;
}
var_dump($data) // Array with all the data. Note that this is now a 2-d array.
Let me know if this works
I´ve got the following JSON string:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}},"recipes_id":{"ranking_1":"9","ranking_2":"10","ranking_3":"7","ranking_4":"5"}},"Message":null,"Code":200}
How can I parse it in PHP and extract a list of TITLEs?
You can use the function json_decode to parse JSON data in PHP (>= 5.2.0, at least). Once you have a PHP object, it should be easy to iterate over all recipes/members and access their titles, using something like this:
$data = json_decode($json, true); // yields associative arrays instead of objects
foreach ($data['Data']['Recipes'] as $key => $recipe) {
echo $recipe['TITLE'];
}
(Sorry I can't actually run this code right now. Hope it helps anyway.)
If you want to do that in JavaScript, you can simply access JSON data like "normal" objects:
var jsonData = {
"Data": {"Recipes": {"Recipe_5": {"ID":"5","TITLE":"Spaghetti Bolognese"}}}
// more data
};
alert(jsonData.Data.Recipes.Recipe_5.TITLE);
This will print the TITLE of Recipe_5 in a message box.
EDIT:
If you want all the titles in a list, you can do something like this:
var titles = [];
for (var key in jsonData.Data.Recipes) {
var recipe = jsonData.Data.Recipes[key];
titles.push(recipe.TITLE);
}
alert(titles);