I have the following code in a codeigniter REST app (built using: https://github.com/chriskacerguis/codeigniter-restserver)
public function fullname_get()
{
$fullname = array("fname"=>"john", "lname"=>"doe");
$data["json"] = json_encode($fullname);
$this->response($data["json"], 200);
}
When I call the API, this return json that looks like this:
{\"fname\":\"john\",\"lname\":\"doe\"}
The above json string fails http://jsonlint.com/ test because of the escape character "\".
Just wondering how I can work around this?
I'm building a REST api that is supposed to return json ... and I have to make sure it's legit json.
Thanks.
Try this
$fullname = array("fname"=>"john", "lname"=>"doe");
$this->response($fullname, 200);//it sends data json format. You don't need to json encode it
You got that response because your data is json encoded twice
You have to strip slashes, use this stripslashes(json_encode($fullname)). Full code mention below:
public function fullname_get()
{
$fullname = array("fname"=>"john", "lname"=>"doe");
$data["json"] = stripslashes(json_encode($fullname));
$this->response($data["json"], 200);
}
I hope this will solve your issue.
It is legit JSON - and you didn't write a test ;)
{
"fname": "john",
"lname": "doe"
}
Please see the demo over at http://ideone.com/5IW1Ef
The class you are using does magical things:
$this->response($this->db->get('books')->result(), 200);
and based on the format specified on the URL the response data is converted to JSON. You don't have to do the JSON encoding.
Please read the examples provides here
https://github.com/chriskacerguis/codeigniter-restserver#responses
$fullname = array("fname"=>"john", "lname"=>"doe");
$this->response($fullname, 200);
http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814
Related
I have array like below.
$resultArr = array();
$resultArr['status code'] = 200;
$resultArr['result'] = "Success";
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
return $json;
This is giving result like below
"{\n \"status code\": \"200\",\n \"result\": \"Success\",\n}"
without Pretty_print the result is like below
"{\"status code\":\"200\",\"result\":\"Success\"}"
I want response to be like this
{
"status code": 200,
"result": "Success"
}
Is something like this can be done pls, I am using PHP, Running the request in postman and the response are mentioned above
Note: I need to avoid using echo, because we are using code sniffers in project, so echo is not recommended.
You used JSON_PRETTY_PRINT for beautify output purpose,
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
If you want to use it as response remove that parameter,
$json = json_encode($resultArr);
Above line should work.
First of all, remove the JSON_PRETTY_PRINT flag.
Secondly, your problem is with the backslashes (\). These are escape characters. I don't know how you are printing your json or how you are viewing it.
If I do:
echo $json;
It outputs:
{"status code":200,"result":"Success"}
The backslashes are probably added because you're doing an AJAX request. In order to solve this, you could use jQueries .parseJSON() or add dataType: "json" to your ajax request.
And if you really don't want the backslashes to be added:
$json = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
Update
It might help to output using the following header:
header('Content-Type: application/json');
1. for Output Of API You Can Use Api:
header('Content-Type: application/json');
2. Using JSON_PRETTY_PRINT
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
3. You want To Display In Chrome
https://addons.mozilla.org/en-US/firefox/addon/json-handle/?src=recommended
I am using currencylayer JSON API to get realtime currency conversion value - does anybody know how I could grab both the "result" value and the "quote" value from the API response below using PHP?
I am new to PHP, and I am wondering if it's possible to store it in a variable.
This is the JSON:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"query":{
"from":"CAD",
"to":"GBP",
"amount":234
},
"info":{
"timestamp":1432829168,
"quote":0.524191
},
"result":122.660694
}
I have played around with file_get_contents("URL") but I didnt understand how to get a single value out.
Request URL looks like this:
https://apilayer.net/api/convert?access_key=...&from=CAD&to=GBP&amount=234
Thanks for the help!
Ok, lets say that json response is in a variable named $response, you must use json_decode and then do as follows:
$decoded = json_decode($response);
$result = $decoded->result;
$quote = $decoded->info->quote;
var_dump($result, $quote);
Try this
$jsonArray = file_get_contents($yourUrl);
$jsonObject = json_decode($jsonArray);
echo $jsonObject->result;
echo $jsonObject->info->quote;
I have the following code in a codeigniter REST app (built using: https://github.com/chriskacerguis/codeigniter-restserver)
public function fullname_get()
{
$fullname = array("fname"=>"john", "lname"=>"doe");
$data["json"] = json_encode($fullname);
$this->response($data["json"], 200);
}
When I call the API, this return json that looks like this:
{\"fname\":\"john\",\"lname\":\"doe\"}
The above json string fails http://jsonlint.com/ test because of the escape character "\".
Just wondering how I can work around this?
I'm building a REST api that is supposed to return json ... and I have to make sure it's legit json.
Thanks.
Try this
$fullname = array("fname"=>"john", "lname"=>"doe");
$this->response($fullname, 200);//it sends data json format. You don't need to json encode it
You got that response because your data is json encoded twice
You have to strip slashes, use this stripslashes(json_encode($fullname)). Full code mention below:
public function fullname_get()
{
$fullname = array("fname"=>"john", "lname"=>"doe");
$data["json"] = stripslashes(json_encode($fullname));
$this->response($data["json"], 200);
}
I hope this will solve your issue.
It is legit JSON - and you didn't write a test ;)
{
"fname": "john",
"lname": "doe"
}
Please see the demo over at http://ideone.com/5IW1Ef
The class you are using does magical things:
$this->response($this->db->get('books')->result(), 200);
and based on the format specified on the URL the response data is converted to JSON. You don't have to do the JSON encoding.
Please read the examples provides here
https://github.com/chriskacerguis/codeigniter-restserver#responses
$fullname = array("fname"=>"john", "lname"=>"doe");
$this->response($fullname, 200);
http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814
I'm trying to display search-results with the sign & in them. But when I render from php to json & converts to &.
Is there anyway I can prevent that, or before I print the names in the search-bar convert it back to &?
Thanks in advance!
EDIT:
HTML JS:
{
name: 'industries',
prefetch: 'industries_json.json',
header: '<h1><strong>Industries</strong></h1>',
template: '<p>{{value}}</p>',
engine: Hogan
},
industries_json.json (Created with json_encode)
[{"id":42535,"value":"AUTOMOBILES & COMPONENTS","type":"industries"}]
php-script which ouputs json:
public function renderJSON($data){
header('Content-type: application/json');
echo json_encode($data);
}
Use html_entity_decode function like...
Code Before:
public function renderJSON($data){
header('Content-type: application/json');
echo json_encode($data);
}
output: Gives html code in string like ex: appthemes & Vantage search Suggest
Code After:
public function renderJSON($data){
header('Content-type: application/json');
$data = json_encode($data);
echo html_entity_decode( $data );
}
output: Gives html code in string like ex: appthemes & Vantage search Suggest
The issue you're facing is HTML encoding. What you want is to decode the text before sending it to the client. It is important that you only decode the text properties of the JSON object (rather than the entire JSON object itself).
Here is a reference on HTML decoding in PHP: http://php.net/manual/en/function.html-entity-decode.php
I would do it in javascript. Once you have got the JSON, just use replace function of javascript on the JSON like this:
first convert it to string by this:
var jsonString=JSON.stringify(jsonData);
then replace & like this.
jsonString=jsonString("&","&");
then again, convert it to JSON obj;
jsonObj=JSON.parse(jsonString);
now, your JSON, will have & instead of &.
What's next ?
Do whatever you need to do with the jsonObj
I just created an account on 500px.com, and would like to use their API: http://developer.500px.com/
But it looks like it cant return JSONP, only JSON.
Is there any way to make a php file that you can post a url to -> make it convert the response from the api from JSON to JSONP, so i can handle it on the client side?
I havent been writing any PHP in a long time, so any help is appreciated. Hope you get the idea, otherwise ill elaborate. Thanks
Sure you can. The only difference between JSON and JSONP is that JSONP is wrapped with a function name;
{ "x": "hello" } // JSON
foo({ "x": "hello" }); // JSONP.
In it's simplest form you can end up with something like this;
<?php echo $_GET['callback']; ?>(<?php echo file_get_contents($_GET['endpoint']); ?>);
and you'd expect clients to use it like this;
http://yourserver.com/proxy.php?endpoint=https%3A%2F%2Fapi.500px.com%2Fv1%2Foauth%2Fauthorize&callback=foo
Note the encoded URL and the addition of the callback parameter to know which function to invoke.
Of course, you'll need to valid the input; check the existance of the parameters, check the endpoint passed isn't malicious etc. You might want to also cache the responses on your server to stop you reaching any limits imposed on the API.
Something more resilient against malicious input could look like;
// checks for existence, and checks the input isn't an array
function getAsString($param) {
if (is_null($_GET[$param]) || !is_string($_GET[$param])) {
return '';
}
return $_GET[$param];
}
$endpoint = getAsString('endpoint');
// check callback is only alpha-numeric characters
$callback = preg_replace('/[^\w\d]/', '', getAsString('callback'));
// check the endpoint is for the 500px API
$is_api = (strpos($endpoint, 'https://api.500px.com') === 0);
if (strlen($callback) > 0 && $is_api) {
echo $callback . '(' . file_get_contents($endpoint) . ')'
} else {
// handle error
}