Return JSON inside data[] php - php

I'm using the following to pull some data fro facebook:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
echo $tagData;
This produces e.g.:
{"data":
[
{"name":"Jonathan Montiel","id":"28125695"},
{"name":"Jackson C. Gomes","id":"51300292"}
],
"paging":{"next":"https:\/\/graph.facebook.com\/123456789\/friends?access_token=5148835fe&limit=5000&offset=5000&__after_id=100060104"}}
QUESTION How I can just return ONLY what's inside the [...] including the [ ]?
Desired result:
[
{"name":"Jonathan James","id":"28125695"},
{"name":"Jackson C. Cliveden","id":"51300292"}
]

Try this:
$tagData = json_decode( $tagData, true );
$data = $tagData['data'];
echo json_encode( $data );
This basically converts the JSON to an array, extracts the desired part and returns this again as JSON-encoded.
EDIT
Example Fiddle

json_decode and reencode with json_encode necessary part of the response. Following is going to work for you:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
$tagData = json_decode($tagData);
echo json_encode($tagData->data);

Thanks to Sirco for the inspiration, this works although how its different to answer given I have no clue!
$tagData = json_decode(file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token), true );
$data = $tagData['data'];
echo json_encode( $data );

Related

How to Parse this JSON (PHP & JSON_DECODE)

I am using the following API: https://openweathermap.org and it gives a JSON response to get the current weather.
{
"coord":{
"lon":
"lat":
},
"weather":[
{
"id":521,
"main":"Rain",
"description":"shower rain",
"icon":"09n"
}
],
"base":"stations",
"main":{
"temp":289.22,
"pressure":1004,
"humidity":82,
"temp_min":288.15,
"temp_max":290.15
},
"visibility":10000,
"wind":{
"speed":4.1,
"deg":210
},
"clouds":{
"all":100
},
"dt":1501793400,
"sys":{
"type":1,
"id":5060,
"message":0.0039,
"country":"GB",
"sunrise":1501734589,
"sunset":1501790444
},
"id":3333126,
"name":"Borough of Blackburn with Darwen",
"cod":200
}
What is the correct way to go about getting the main and description in the JSON?
I have attempted the code below but it doesn't work:
$url = "http://api.openweathermap.org/data/2.5/weather?lat=" . $latitude . "&lon=" . $longitude . "&APPID=71f4ecbff00aaf4d61d438269b847f11";
$dirty_data = file_get_contents( $url );
$data = json_decode( $dirty_data );
echo $data['weather']['main'];
When using json_decode() to convert json data to php type, it will always convert it into an object. To be clear you can access weather's main and description property like this:
echo $data->weather[0]->main // outputs main
echo $data->weather[0]->description // outputs description
Update:
Besides you can also convert data into an associative array by passing bool(true) $assoc argument to the json_decode() function.
$data = json_decode( $dirty_data, true );
And extract your data like this:
echo $data['weather'][0]['main']; // for main
echo $data['weather'][0]['description']; // for description
Yo can always do var_dump($data) to see what you have and how to access it.
json_decode returns a stdClass not an array.
$data->weather[0]->main;
Should be the right thing.
{} symbolizes an object and [] symbolizes an array. Notice weather:[{...}] which means weather is an array of objects.
Try
$data = json_decode( $dirty data, true)
It doesn't convert to an object if you supply the true argument.

Read JSON Data Have Token With PHP

How can I read a JSON data response using php?
This is Code :
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
and give me this json data :
{
"original": "This sentnce has some probblems.",
"suggestion": "This sentence has some problems.",
and ...
}
I want to return "suggestion" in a url with $
this is an example :
$user_id = '123456789'
$mytext = '?' // I WANT RETURN "suggestion" HERE !
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
You can use json_decode().
See:
http://php.net/manual/en/function.json-decode.php
You just need to do:
$response = json_decode($response,1);
echo $response['suggestion'];
Setting the second parameter of json_decode() to 1 (true) will return an associative array of the JSON data.
If you want to include it in a URL using your code example:
$user_id = '123456789'
$json = json_decode($response,1);
$mytext = $json['suggestion'];
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
Use json_decode to convert json_response to array.Add second parameter of 'true' to make it an array that you should be familiar with.
Access suggestion variable by specifying it.
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
$data=json_decode($response,true);
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion'];
echo $url;

how to remove back slashes from json output in php

The code I have used:
$val = json_encode(array("test"=>test1,"test2" =>test,"description" => description));
return $val;
The result im getting
{\"test\":\"test1\",\"test2\":\"test\",\"description\":\"description\"}
I need this to fix api
Try with stripslashes()
echo stripslashes('{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}');
stripslashes()
Tried this.
$val = json_encode(array(
"test"=>'test1',
"test2" =>'test',
"description" => 'description'
));
$data = json_decode($val, true, JSON_UNESCAPED_SLASHES);
return $data;
This is the result I received.
In php "stripslashes" function is present using that you can remove backslash.
Link for more details.
Example:
echo $strnew = stripslashes('{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}');
Use stripslashes() And read stripslashes
<?php
$srt="'{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'
";
echo stripslashes($srt);
OUTPUT
'{"test":{"test1":{"test1":[{"test2":"1","test3":
"foo","test4":"bar","test5":"test7"}]}}}'
you can use JSON_UNESCAPED_SLASHES
json_encode($yourjson, JSON_UNESCAPED_SLASHES);
Use string find and replace function
$str="{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}";
str_replace("\'","'",$str);
Try the following code. It works perfectly fine for me $cha a string with backslashes
$cha = "{\"ashen\":\"143\"}";
$chachi = json_decode($cha,JSON_UNESCAPED_SLASHES);
return $chachi['ashen'];
output: 143
Actually, only Khachornchit Songsaen answer is correct.
stripslashes does not work on unescaping escaped " in json encoded strings inside another json.
es.
{ "key1" :"value1", "key2": "{\"key\":\"Text \\\"text\\\" text\"}" }
using json_decode($var, true, JSON_UNESCAPED_SLASHES) does the job correctly.
this is the right method when your result is coming in slashes do this
$data = [
"message" => '',
"data" => $product
];
$response[] = $data;
return $response;
do this it's really work because after 5 day i fund this solution or it is right .
I was facing same issue, it is resolved by using echo and exit;
$response = json_encode(array("test"=>"test1","test2"
=>"test","description" => "description"));
echo $response;
exit;

How to include a php variable in json and pass to ajax

My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result, it shows "$result", instead of showing Hello.
How can I solve this?
The basic problem with your example is that $result is wrapped in single-quotes. So the first solution is to unwrap it, eg:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
But this is still not "good enough", as it is always possible that $result could contain a " character itself, resulting in, for example, {"result":""","count":3}, which is still invalid json. The solution is to escape the $result before it is inserted into the json.
This is actually very straightforward, using the json_encode() function:
$result = 'Hello';
echo '{
"result":'.json_encode($result).',
"count":3
}';
or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just $result:
$result = 'Hello';
echo json_encode(array(
'result' => $result,
'count' => 3
));
You should use json_encode to encode the data properly:
$data = array(
"result" => $result,
"count" => 3
);
echo json_encode($data);
You're using single quotes in your echo, therefore no string interpolation is happening
use json_encode()
$arr = array(
"result" => $result,
"count" => 3
);
echo json_encode($arr);
As a bonus, json_encode will properly encode your response!
Try:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
$result = 'Hello';
$json_array=array(
"result"=>$result,
"count"=>3
)
echo json_encode($json_array);
That's all.

PHP Use regex to find and remove a variable in a string

With PHP, I'm opening a file and it looks like this:
var people = {
vikram: { time1: [ '8:00am', '8:20am', '8:40am', '9:00am', ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am', ], time3: [ '8:00am', '8:20am', '8:40am', ], }};
The variable I'm trying to remove will contain a time (ex. 8:00am) and I will know the timeIndex(ex. time1). I also want to keep all the other times intact.
For example, if I set the variable to 8:40am, I want the new file that is being created to look like this:
var people = {
vikram: { time1: [ '8:00am', '8:20am', '9:00am', ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am', ], time3: [ '8:00am', '8:20am', '8:40am', ], }};
Any help would be appreciated!
The format you show represents a JSON formatted string. You can use json_decode() function to make an array from string, then loop through the array and just unset() the element you don't need.
you can use preg_replace() for this:
<?php
$filename = 'yourfile.js';
$search = '8:40am';
$content = file_get_contents( $filename );
$pattern = '/(\s*time1:\s*\[.*)([\'"]' .
preg_quote($search) .
'[\'"],?\s*)(.*\])/U';
$content = preg_replace( $pattern, '\1\3', $content );
file_put_contents( $filename, $content );
?>
This is a modification of the code example i answered to your last question on a similar topic.
Here is the way I did it. Basically, I use json_decode to parse your json to php object. However, I also found that your input is not a well-formed json for php (See example 3). Although my code doesn't look good and generic, but I hope it will help you.
<?php
$json_data = '{
"vikram": {
"time1": ["8:00am", "8:20am", "8:40am", "9:00am"],
"time2": ["10:20am", "10:40am", "11:00am", "11:20am"],
"time3": ["8:00am", "8:20am", "8:40am"]
}
}';
$obj = json_decode($json_data);
//var_dump($obj->vikram);
$value = "8:40am";
$time1 = "time1";
$delete_item;
foreach($obj->vikram as $name=>$node)
{
foreach($node as $i => $time)
{
if($time==$value && $name=$time1)
{
$delete_item = $i;
}
}
}
unset($obj->vikram->time1[$delete_item]);
var_dump($obj->vikram);

Categories