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
Related
I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.
You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()
I have the JSON code below. According to one or two JSON validators it is valid JSON.
{
"patterns": {
"email": "/[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,}/i",
"phone": "/(?:(?:\\(?(?:0(?:0|11)\\)?[\\s-]?\\(?|\\+)44\\)?[\\s-]?(?:\\(?0\\)?[\\s-]?)?)|(?:\\(?0))(?:(?:\\d{5}\\)?[\\s-]?\\d{4,5})|(?:\\d{4}\\)?[\\s-]?(?:\\d{5}|\\d{3}[\\s-]?\\d{3}))|(?:\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{3,4})|(?:\\d{2}\\)?[\\s-]?\\d{4}[\\s-]?\\d{4}))(?:[\\s-]?(?:x|ext\\.?|\\#)\\d{3,4})?/"
}
}
However, when I try to decode using in PHP using the json_decode function I get a 'Syntax Error'. Here's my PHP code:
const JSON_CONFIG = <<<JSON
{
"patterns": {
"email": "/[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,}/i",
"phone": "/(?:(?:\\(?(?:0(?:0|11)\\)?[\\s-]?\\(?|\\+)44\\)?[\\s-]?(?:\\(?0\\)?[\\s-]?)?)|(?:\\(?0))(?:(?:\\d{5}\\)?[\\s-]?\\d{4,5})|(?:\\d{4}\\)?[\\s-]?(?:\\d{5}|\\d{3}[\\s-]?\\d{3}))|(?:\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{3,4})|(?:\\d{2}\\)?[\\s-]?\\d{4}[\\s-]?\\d{4}))(?:[\\s-]?(?:x|ext\\.?|\\#)\\d{3,4})?/"
}
}
JSON;
$config = json_decode(mb_convert_encoding(JSON_CONFIG, "UTF-8"), true); // Tried called trim but it made no difference
echo 'json_last_error_msg() => ' . json_last_error_msg() . PHP_EOL;
print_r($config); // Doesn't get to run
Try for yourself: https://repl.it/#DanStevens/PHP-jsondecode-Syntax-Error
Any ideas what json_decode isn't liking this valid JSON? Is it related to the use of HEREDOC?
The backslashes are acting as PHP escape sequences, not JSON escape sequences. To prevent PHP escaping, surround your heredoc start token in single quotes:
const JSON_CONFIG = <<<'JSON'
{
"patterns": {
"email": "/[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,}/i",
"phone": "/(?:(?:\\(?(?:0(?:0|11)\\)?[\\s-]?\\(?|\\+)44\\)?[\\s-]?(?:\\(?0\\)?[\\s-]?)?)|(?:\\(?0))(?:(?:\\d{5}\\)?[\\s-]?\\d{4,5})|(?:\\d{4}\\)?[\\s-]?(?:\\d{5}|\\d{3}[\\s-]?\\d{3}))|(?:\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{3,4})|(?:\\d{2}\\)?[\\s-]?\\d{4}[\\s-]?\\d{4}))(?:[\\s-]?(?:x|ext\\.?|\\#)\\d{3,4})?/"
}
}
JSON;
var_dump(JSON_CONFIG);
echo PHP_EOL;
$config = json_decode(mb_convert_encoding(JSON_CONFIG, "UTF-8"), true); // Tried called trim but it made no difference
echo 'json_last_error_msg() => ' . json_last_error_msg() . PHP_EOL;
echo 'json_last_error() => ' . json_last_error() . PHP_EOL;
print_r($config);
Repl: https://repl.it/repls/AmusedOvercookedEmbed
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>';
}
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.
I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.