Selecting Data from JSON object using php - getjson

I have json data i want to select some data before i tell you please read the data carefully.
{
"response": {
"status": 1,
"httpStatus": 200,
"data": [{
"offer_id": "6912",
"Thumbnail": {
"10116": {
"id": "10116",
"offer_id": "6912",
"display": "Icandytv_IN_Call-30-19-20-51).gif",
"thumbnail": "https:\/\/media.go2speed.org\/brand\/files\/mobvista\/6912\/thumbnails_100\/Icandytv_IN_Call(04-30-19-20-51).gif"
}
}
}],
"errors":[] ,
"errorMessage": null
}
}
From above Data i want to collect the value of thumbnail plese help me to find it out using PHP

Maybe that is an copy/paste problem, but your JSON-String is missing some }. But that is not the issue. If you want to access thumbnail (lowercase) in your json, try following:
<?php
$json = '{"response": {"status":1,"httpStatus":200,"data":[{"offer_id":"6912","Thumbnail":{"10116":{"id":"10116","offer_id":"6912","display":"Icandytv_IN_Call (04-30-19-20-51).gif","thumbnail":"https://media.go2speed.org/brand/files/mobvista/6912/thumbnails_100/Icandytv_IN_Call(04-30-19-20-51).gif"}}}],"errors":[],"errorMessage":null}}';
// Make JSON accessible for PHP
$data = json_decode($json);
// Get access to Thumbnail object
$thumbnail0 = $data->response->data[0]->Thumbnail;
// Get access to thumbnail object "10116"
$thumbnail_10116 = $thumbnail0->{"10116"};
// Thumbnail Url
$thumbnailUrl = $thumbnail_10116->thumbnail;
echo $thumbnailUrl . "\n";
// or in one swoop
$thumbnailUrl2 = $data->response->data[0]->Thumbnail->{"10116"}->thumbnail;
echo $thumbnailUrl2 . "\n";
?>
Hope, that helps

Related

How can I configure Flutter to use two different APIs?

I have a Flutter app and I would like to call multiple API endpoints which use different databases.
I don't know if I should do this on the backend or the frontend.
api1.php:
<?php // header('Content-Type: application/json');
include "config.php";$sql = "select inventeries.pic_inv,inventeries.name,site.Sname,users.number from inventeries,site,users";
$stmt = $con->prepare($sql);
$stmt->execute();
$med = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($med);
?>
api_2.php:
<?php
// header('Content-Type: application/json');
include "config.php";
$sql = "select users.pic_inv,users.name,site.Sname,users.number from users,site,users";
$stmt = $con->prepare($sql);
$stmt->execute();
$med = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($med);
?>
Currently they use the same database, so the results from both APIs are the same:
{"pic_inv":"ACICAL-PLUS.jpg","name":"Aclcal","Sname":"flowers pharma","number":"7894561231"}
{"pic_inv":"ACICAL-PLUS.jpg","name":"Aclcal","Sname":"flowers pharma","number":"123456789"}
{"pic_inv":"what-a-treatment-for-migraine-headache.jpg","name":"foar","Sname":"flowers pharma","number":"7894561231"}
{"pic_inv":"what-a-treatment-for-migraine-headache.jpg","name":"foar","Sname":"flowers pharma","number":"123456789"}
{"pic_inv":"syrunj.png","name":"AMLO","Sname":"flowers pharma","number":"7894561231"}
{"pic_inv":"syrunj.png","name":"AMLO","Sname":"flowers pharma","number":"123456789"}
{"pic_inv":"cap.jpg","name":"pandol","Sname":"flowers pharma","number":"7894561231"}
{"pic_inv":"cap.jpg","name":"pandol","Sname":"flowers pharma","number":"123456789"}
Well, as i have said, i have no experience with PHP and all would be easier in the API..
but you can make a model in your flutter app like lets say the data you get from DB1 endpoint is like this
{
"inventeries.pic_inv" : "something",
"inventeries.name" : "something",
"site.Sname" : "something",
"users.number" : "something"
}
and the data you get from DB2 Endpoint is like this
{
"users.pic_inv" : "something",
"users.name" : "something",
"site.Sname" : "something",
"users.number" : "something"
}
then you prepare a model that combines all to be something like this.. lets call it MixedModel
{
//Mixed both data and get only the data you want..
"users.pic_inv" : "something",
"users.name" : "something",
"inventeries.pic_inv" : "something",
"inventeries.name" : "something"
"site.Sname" : "something",
"users.number" : "something",
}
you can use https://app.quicktype.io/ to generate the models for your data.
then you can make a function that can make a call to both of the endpoints
im using Dio Package to make the API Calls..
Future<List<MixedModel>> GetDataFromADatabase() async {
try{
String URL_ENDPOINT_ONE = "URL TO ENDPOINT 1";
String URL_ENDPOINT_TWO = "URL TO ENDPOINT 2";
var ResponseOne = await Dio().get(URL_ENDPOINT_ONE);
var ResponseTwo = await Dio().get(URL_ENDPOINT_TWO);
if(ResponseOne.statusCode == 200 && ResponseTwo.statusCode == 200){
// only if both requests are successful
var data = jsonDecode(ResponseOne.data.toString()) as List<MixedModel>;
//combine data
data.addAll(json.decode(ResponseTwo.data.toString()) as List<MixedModel>);
return data;
}
List<MixedModel> empty = [];
return empty;
}
catch (ex){
List<MixedModel> empty = [];
if(ex is dio.DioError){
print( ex.response);
}
return empty;
}
}
I hope you get the idea

Perl get all values from hahes inside of array

I`m really struggling with Perl and I need to solve this topic. I Have a rest api response that I converted to json, Dumper shows something like this:
VAR1= [
{
"id":"abc",
"type":"info",
"profile":
{"name":"Adam",
"description":"Adam description"}
},
{
"id":"efg",
"type":"info",
"profile":
{"name":"Jean",
"description":"Jean description"}
},
{
"id":"hjk",
"type":"info",
"profile":
{"name":"Jack",
"description":"Jack description"}
},
]
What I need is to iterate over each "name" and check if value is Jean. I wanted to iterate over hashes inside of array, but each time it will only store first hash, not all of them.
What I`m trying and failing:
# my json gather, Dumper is shown above.
my $result_json = JSON::from_json($rest->GET( $host, $headers )->{_res}->decoded_content);
# I`ve tried many things to get all hashes, but either error, or single hash, or single value:
my $list = $result_json->[0];
my $list2 = $result_json->[0]->{'profile'};
my $list3 = #result_json->[0];
my $list4 = #result_json->[0]->{'profile'};
my $list5 = #result_json;
my $list5 = #result_json->{'profile'}; # this throws error
my $list6 = #result_json->[0]->{'profile'}->{'name'};
my $list7 = $result_json->[0]->{'profile'}->{'name'};
# and maybe more combinations... its just an example.
foreach my $i (<lists above>){
print $i;
};
Any idea how to set it up properly and iterate over each "name"?
Assuming that the call to JSON::from_json shown in the code smaple is indeed given the JSON string shown as a Dumper output,† that $result_json is an array reference so iterate over its elements (hash references)
foreach my $hr (#{ $result_json }) {
say "profile name: ", $hr->{profile}{name};
}
† That last comma in the supposed Dumper's output can't actually be there, so I removed it to use the rest as a sample JSON for testing

What to do when an API has no documentation

I'm currently trying to use a REST API to insert data from Powershell into a Jira custom field made by a certain plugin (Easy links for JIRA). Unfortunately there's no documentation on the required syntax. Does anyone who's run into this plugin know the commands/syntax I'll need to use the REST API (It's quite a small plugin so I'll be surprised if anyone else has seen it)? Failing that, does anyone have any advice on discovering how to use APIs with no/bad documentation i.e. some standard method of making an API return a list of commands and syntax (preferably by using powershell)?
I've tried contacting the developer but haven't heard back from them.
The code I'm using is here, if that's helpful:
function Test-Upload(){
Param()
Process{
$data=#"
{
"fields":
{
"project":
{
"key": "CCWASSET"
},
"summary": "Testing Linked Field",
"issuetype":
{
"name": "Asset"
},
"description" : "Testing Linked Field"
},
"update":{
"customfield_10500":[
{
"set":{
"type":{
"name":"Asset PO",
"inward":"Asset",
"outward":"Purchase Order"
},
"outwardIssue":{
"key":""
}
}
}
]
}
}
"#
return Jira-WebRequest -data $data
}
}
function Jira-WebRequest(){
Param(
[Parameter(mandatory=$false)]$data,
[Parameter(mandatory=$false)]$requesttype="issue",
[Parameter(mandatory=$false)]$method="POST",
[Parameter(mandatory=$false)]$ContentType='application/json'
)
Process{
$path = $("/rest/api/2/$requesttype/")
$Uri = ""
[URI]::TryCreate([URI]::new($Settings.Jira.URL),"$path",$([ref]$Uri))
$Params = #{
ContentType = $ContentType
Body = $data #$(#{"vlan_id"=$vlanID;"port_id"="$portID";"port_mode"="$portMode"} | ConvertTo-JSON)
Method = $method
URI = $uri.AbsoluteUri
Headers = $JiraHeaders
#WebSession = $Session
}
try{
$result = Invoke-RestMethod #Params -Verbose
return $result
} Catch [System.Net.WebException] {
$exception = $_.Exception
$respstream = $exception.Response.GetResponseStream()
$sr = new-object System.IO.StreamReader $respstream
$ErrorResult = $sr.ReadToEnd()
return $ErrorResult
}
}
}
It doesn't matter if the custom field made by a plugin or by you. At the end it's custom field so since the plugin doesn't have a good documentation, I would recommend you to stay with Atlassian Documentation and update / edit your issues base on official REST API. You can see Atlassian examples with Custom Fields here
What you need to do is you just need to figure out what's the custom field ID and that would be easy by going towards admin panel and clicking on the custom field and check it from URL if you don't want to go to database.
I know it's pain to see API without documents but at least you can workaround it this way.
Managed to get it working for this particular plugin. Had to include the ID field as well as the Key of the issue that I want to link to. I'd still be interested to hear if anyone has some tips for working with API's that have no/bad documentation.
"update":{
"customfield_10500":[
{
"set":{
"type":{
"name":"Asset PO",
"inward":"Asset",
"outward":"Purchase Order"
},
"outwardIssue":{
"key":""
"ID":""
}
}
}
]
}
}

WooCommerce REST API - how to get product resized images url?

all images in wordpress will auto resize and save in uploads folder like this:
sample_product_image-100x100.png
sample_product_image-150x150.png
sample_product_image-180x113.png
sample_product_image-300x189.png
...
sample_product_image-555x349.png
sample_product_image-600x378.png
sample_product_image.png (original large file)
for faster loading I need smaller size of product image in rest api like this one:
sample_product_image-300x189.png
but woocommerce rest api just send me original largest file (sample_product_image.png):
"images": [
{
"id": 7291,
"date_created": "2018-06-12T03:17:03",
"date_created_gmt": "2018-06-11T13:47:03",
"date_modified": "2018-06-12T03:17:03",
"date_modified_gmt": "2018-06-11T13:47:03",
"src": "http://example.com/wp-content/uploads/2018/06/sample_product_image.png",
"name": "sample_product_image",
"alt": "",
"position": 0
},
how can I get smaller image urls in wc rest api?
btw I found this plugin for wordpress rest api that is not working for woocommerce.
found a solution here.
Just need to add this filter to your theme's function.php
function prepare_product_images($response, $post, $request) {
global $_wp_additional_image_sizes;
if (empty($response->data)) {
return $response;
}
foreach ($response->data['images'] as $key => $image) {
$image_urls = [];
foreach ($_wp_additional_image_sizes as $size => $value) {
$image_info = wp_get_attachment_image_src($image['id'], $size);
$response->data['images'][$key][$size] = $image_info[0];
}
}
return $response;
}
add_filter("woocommerce_rest_prepare_product_object", "prepare_product_images", 10, 3);
Also if you need only 1 special size you can remove second foreach and manually initialize $size to 'thumbnail' , 'medium' , 'medium_large' or 'large'

List facebook likes underneath every url

I was trying to find the best way to count number of likes for a facebook page url and after googling a lot and playing with the code, i have a code like the one given below. It outputs the likes, name of the page and then the link. I wish to know:
1. How can i use the html tag to convert the link into hyperlink so that I can have something like "Click here to visit"
2. How can monitor performance of 25+ fb_id on an hourly basis with a sorted order (descending) on likes
<?php
$fb_id = '36922302396';
$url = 'https://graph.facebook.com/' . urlencode($fb_id);
$result = json_decode( file_get_contents($url) );
printf("%s %s %s", $result->likes, $result->name, $result->link);
?>
Edited code as per solution provided
<?php
$fb_id = '36922302396';
$pic = 'https://www.facebook.com/' . urlencode($fb_id) . '/picture?type=square';
$url = 'https://graph.facebook.com/' . urlencode($fb_id);
$result = json_decode( file_get_contents($url) );
echo $result->likes , " " , $result->name , " " , "<a target='_blank' href=\"" . $result->link . "\" ><img src = $pic></a>";
?>
Thanks
For 1)
How about
<?php
$fb_id = '36922302396';
$url = 'https://graph.facebook.com/' . urlencode($fb_id);
$result = json_decode( file_get_contents($url) );
//printf("%s %s %s", $result->likes, $result->name, $result->link);
echo "Link";
?>
You can also use
Link
For 2)
If you know the Page's IDs, then you can just concatenate them to the following :
GET /?ids=40796308305,339150749455906&fields=id,name,likes,talking_about_count
The result looks like the following
{
"40796308305": {
"id": "40796308305",
"name": "Coca-Cola",
"likes": 88365218,
"talking_about_count": 635936
},
"339150749455906": {
"id": "339150749455906",
"name": "Pepsi",
"likes": 33321925,
"talking_about_count": 208761
}
}
For hourly stats, you need to setup your script via cron etc. and write the results to a database.