Looping through JSON response from desk.com API - php

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

Related

Parse JSON & remove items in PHP

So, I have some JSON data that looks like this:
{
"Table1":[
{
"CURRENCY_FLAG":"EUR",
"TRADE_DATE":"2015-10-15",
"DELIVERY_DATE":"2015-10-15",
"DELIVERY_HOUR":"7",
"DELIVERY_INTERVAL":"1",
"RUN_TYPE":"EA",
"SMP":"35.370",
"LAMBDA":"35.370",
"SYSTEM_LOAD":"3164.611",
"CMS_TIME_STAMP":"2015-10-14T10:03:09+01:00"
},
{
"CURRENCY_FLAG":"GBP",
"TRADE_DATE":"2015-10-15",
"DELIVERY_DATE":"2015-10-15",
"DELIVERY_HOUR":"7",
"DELIVERY_INTERVAL":"1",
"RUN_TYPE":"EA",
"SMP":"26.460",
"LAMBDA":"26.460",
"SYSTEM_LOAD":"3164.611",
"CMS_TIME_STAMP":"2015-10-14T10:03:09+01:00"
}... etc
I'm pretty basic at PHP, but have fetched this data with CURL, and now I want to iterate through this data and remove every node with the "GBP" value for "CURRENCY_FLAG" and just hang onto those with the "EUR" sign.
Can anyone point me in the right direction of parsing this with PHP?
Thanks!
Try simply this way after decoding your json string using json_decode()
//decode json string
$result = json_decode($curl_result, true);
$final_result = [];
foreach($result['Table1'] as $key => $value){
if($value['CURRENCY_FLAG'] != 'GBP'){ //exclude currency flag with GBP
$final_result[] = $value;
}
}
print '<pre>';
print_r($final_result);
print '</pre>';

JSON decode Array and insert in DB

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.

extract JSON variables with php for email use

I'm having difficulty extracting JSON values (obtained by using a URL) into email variables. The following code works (I have removed identifiable and usable data).
$addr = "https://98905:Twmdf56sn0cb#geoip.maxmind.com/geoip/v2.1/insights/".$ipaddr;
// fetching geoip data in JSON format
$json = (file_get_contents($addr));
//parsing JSON format to object format
$obj = json_decode($json);
// assigning values to separate variables for email message
$var_country = $obj->country->names->en;
$var_city = $obj->city->names->en;
$var_city_confidence = $obj->city->confidence->en;
$var_city_geoname_id = $obj->city->geoname_id->en;
$var_location = $obj->location->accuracy_radius->en;enter code here
However one set of data is an array that looks like this (identifiable and usable data scrubbed):
"subdivisions":[{"geoname_id":5166838,"iso_code":"NY","confidence":24,"names":{"ja":"ニューヨーク州","fr":"New York","ru":"Нью-Йорк","en":"New York","zh-CN":"纽约州","de":"New York","pt-BR":"Nova Iorque","es":"Nueva York"}}]
My difficulty lies in extracting the "names" "en" part from the subdivisions multi-array. All the previous arrays are single units, this multi and I'm having difficulty drilling down to the "names" "en" part from subdivisions and getting that value into an array using the same process as above.
If you are just looking to get the en key, you can do something like this:
$objects->subdivisions[0]->names->en;
If you are wanting retrieve each set of data, loop through them like so:
foreach($objects->subdivisions[0]->names as $key => $value) {
echo $key . ' --- ' . $value . '<br />';
}
and modify to your needs.
Try with
$p=json_decode('{"subdivisions":[{"geoname_id":5166838,"iso_code":"NY","confidence":24,"names":{"ja":"ニューヨーク州","fr":"New York","ru":"Нью-Йорк","en":"New York","zh-CN":"纽约州","de":"New York","pt-BR":"Nova Iorque","es":"Nueva York"}}]}');
$enNames = array();
foreach($p->subdivisions as $subdivision){
$enNames[]=$subdivision->names->en;
}
print_r($enNames);

How to get and parse data from geocode farm

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>

Iterate over a JSON response and get results into variables

I am trying to build a simple script that I can pass in a list of Twitter username and it will then access the Twitter API and returns a list of details for the user's that I requested.
Below is what I have so far, it returns a JSON response with all the data for the 3 user's that I sent in the URL.
I need to figure out how to access each of these items, I plan to save them to a database so I need to be able to access the returned items as a variable. Also the number of users/results in the JSON will be different each time depending on how many names I request so I need to somehow iterate over this JSON response.
Can anyone help me?
$json = file_get_contents('http://api.twitter.com/1/users/lookup.json?screen_name=fishriver,metinogtem,friendproject');
$obj = json_decode($json);
echo '<pre>';
print_r($obj);
echo '</pre>';
Iterating is easy:
foreach ($obj as $varName => $varValue)
{
// ...
}
Use foreach to iterate over the JSON object.
$json = file_get_contents('http://api.twitter.com/1/users/lookup.json?screen_name=fishriver,metinogtem,friendproject');
$obj = json_decode($json);
echo '<pre>';
foreach($obj as $index => $user) {
echo $user->screen_name."<br>";
// insert into database here
}
echo '</pre>';

Categories