Parse SendGrid JSON with PHP - php

I have some simple JSON data returned by the SendGrid API:
{
"message":"error",
"errors":[
"some errors"
]
}
I can access the contents of the "message" section via:
$txt = "{\"message\":\"success\"}";
$newtxt = json_decode($txt, true);
echo $newtxt['message'];
That works okay, but I can't work out how to access the contents of the "errors" section?
Sorry, I realise this is probably a silly question.

If your JSON String is this
$tst = '{
"message":"error",
"errors":[
"some errors"
]
}';
Then all you need to so is
$j_array = json_decode($txt, true);
echo $j_array['message'];
echo $j_array['errors'][0];
A better way would be to loop over this array
foreach ($j_array['errors'] as $error ) {
echo $error . '<br>';
}
Of course you dont need to convert everything to an array, you can leave it as written i.e. an object containing properties one of which is an array
$jObj = json_decode($txt);
echo $jObj->message;
echo $jObj->errors[0];
Or
foreach ($jObj->errors as $error ) {
echo $error . '<br>';
}

Related

Proper way to echo JSON in php

Hi i am looking for a proper way to echo json in my php api, currently this is my echo code
I am getting this from a different class
echo '{"accountStatus":{';
echo '"create_status_code": "400",';
echo '"message": "Unable to create user."';
echo '}}';
I am getting this from a different class
echo '{';
echo '"status_code": "em200",';
echo '"message": "email duplicate"';
echo '}';
At the end this is what i am getting which is not valid JSON
{
"status_code":"em200",
"message":"email duplicate"
}{
"accountStatus":{
"create_status_code":"400",
"message":"Unable to create user."
}
}
So please how do i echo it properly?
Don't forget to set the header if you want your browser to properly see it as json:
header('Content-Type: application/json');
echo json_encode(array(
"age" => 4,
"name" => "baby",
));
If you can create the messages as an array, you can use json_encode to get a valid JSON-output:
echo json_encode(array(
"accountStatus" => array(
"create_status_code" => "400",
"message" => "Unable to create user",
),
"status_code" => "em200",
"message" => "email duplicate",
));
For this to work properly, you need proper JSON input or at least convert it to it. If you can change the way the classes output the JSON, make it output it as this:
Using json_decode()
First Class
echo '{"accountStatus":{';
echo '"create_status_code": "400",';
echo '"message": "Unable to create user."';
echo '}}';
Should be a JSON Object:
/* ClassOneOutput */
return json_decode('{
"accountStatus": {
"create_status_code": "400",
"message": "Unable to create user."
}
}', true);
Second Class
echo '{';
echo '"status_code": "em200",';
echo '"message": "email duplicate"';
echo '}';
Should be a JSON Object:
/* ClassTwoOutput */
return json_decode('{
"status_code": "em200",
"message": "email duplicate"
}', true);
Combining them:
/* Main script fetches class output */
$classTwoOutput = classTwo();
$classOneOutput = classOne();
$classOutput = array($classOneOutput, $classTwoOutput);
echo json_encode($classOutput, JSON_PRETTY_PRINT);
It is extremely bad idea. Just use jsonSerialize;
echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
Referenced link

How to access specific value in php and json

I'm using a token:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
and here's the json text(not everything);
{
"success":true,
"data":[{
"id":1,
"creator_user_id":{
"id":1682756,
"name":"Kamilah",
"email":"kamilah#fractal.ae",
"has_pic":false,
"pic_hash":null,
"active_flag":true,
"value":1682756},
"title":"FFS Organization deal"
}]
}
I wanted to display "title" and I always get an error
Notice: Undefined index: creator_user_id in
C:\xampp\htdocs\pipedrive\getjson.php on line 8
Here's my code so far:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo $object['data']['creator_user_id']['title'];
I'm new to json so I'm just practicing and trying to figure out how to echo a specific value in php. Would be appreciated if you can explain exactly how it works when you echo from json to php.
Thank you! :)
First of all you need to debug the array after using json_decode().
<?php
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo "<pre>";
print_r($object); // this will print all data into array format.
?>
As per this array, you do not have title index inside the creator_user_id array. title is a separate index.
Also note that, $object['data'] containing two indexes not one. you can get title as:
<?php
foreach ($object['data'] as $key => $value) {
//print_r($value); // this will print the values inside the data array.
echo $value['title']."<br/>"; // this will print all title inside your array.
}
?>
Result:
FFS Organization deal
Google deal

Decode JSON to PHP

I have a .txt file called 'test.txt' that is a JSON array like this:
[{"email":"chrono#gmail.com","createdate":"2016-03-23","source":"email"}]
I'm trying to use PHP to decode this JSON array so I can send my information over to my e-mail database for capture. I've created a PHP file with this code:
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
echo $json;
?>
For some reason, it's not echoing the decoded JSON when I visit my php page. Is there a reason for this and can anyone shed some light? Thanks!
You use echo to print scalar variables like
$x = 'Fred';
echo $x;
To print an array or object you use print_r() or var_dump()
$array = [1,2,3,4];
print_r($array);
As json_decode() takes a JSON string and converts it to a PHP array or object use print_r() for example.
Also if the json_decode() fails for any reason there is a function provided to print the error message.
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
if ( json_last_error() !== JSON_ERROR_NONE ) {
echo json_last_error_msg();
exit;
}
You'll need to split that json string into two separate json strings (judging by the pastebin you've provided). Look for "][", break there, and try with any of the parts you end up with:
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}

API Data Return to HTML

I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.

PHP: JSON decoding problem

<?php
$handle = fopen("https://graph.facebook.com/search?q=sinanoezcan#hotmail.com&type=user&access_token=2227472222|2.mLWDqcUsekDYK_FQQXYnHw__.3600.1279803900-100001310000000|YxS1eGhjx2rpNYzzzzzzzLrfb5hMc.", "rb");
$json = stream_get_contents($handle);
fclose($handle);
echo $json;
$obj = json_decode($json);
print $obj->{'id'};
?>
Here is the JSON: {"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}
It echos the JSON but I was unable to print the id.
Also I tried:
<?php
$obj = json_decode($json);
$obj = $obj->{'data'};
print $obj->{'id'};
?>
Note that there is an array in the JSON.
{
"data": [ // <--
{
"name": "Sinan \u00d6zcan",
"id": "610914868"
}
] // <--
}
You could try $obj = $obj->{'data'}[0] to get the first element in that array.
data is an array, so it should be:
print $obj[0]->{'id'};
It looks like the key "data" is an array of objects, so this should work:
$obj = json_decode($json);
echo $obj->data[0]->name;
Have you tried $obj->data or $obj->id?
Update: Others have noted that it should be $obj->data[0]->id and so on.
PS You may not want to include your private Facebook access tokens on a public website like SO...
It's a bit more complicated than that, when you get an associative array out of it:
$json = json_decode('{"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}', true);
Then you may echo the id with:
var_dump($json['data'][0]['id']);
Without assoc, it has to be:
var_dump($json->data[0]->id);

Categories