I've followed all the tutorials on printing out a nicely formatted JSON response, but I can't get it to work. If I don't do json_encode PRETTY PRINT, it prints out as a raw JSON result in a single line,
But when I do add all that, it still prints it out as a single line, but with slashes before every quotation mark.
Heres the code I'm using
echo"<pre>";
$response = wp_remote_get( 'URL TO JSON DATA' ));
$jsonData = json_encode($response['body'], JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $jsonData;
echo"</pre>";
And heres a sample of the data being printed out
"{\"head\": {\"error\": \"\", \"version\": \"
I can provide real data if necessary, I just wanted to show what I meant by a slash before every quotation, I'm hoping that's enough to give an idea of my problem
Thanks!
The data you get from wp_remote_get is already a perfectly encoded JSON string, no need to encode again.
When you encode again, PHP generates a structure with one element, the string you originally get, and escapes all the quotes to form valid JSON.
So you can output the data directly :
$response = wp_remote_get( 'URL TO JSON DATA' ));
header('Content-Type: application/json');
echo $response;
Related
I have the following code that converts json into an array:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
$jarray = json_decode($decodedstr, true);
echo "<pre>";
print_r($jarray);
echo "</pre>";
but my $jarray keeps returning null... I dont know why this is happening.. i have already validated my json in this question:
validated json question could anyone tell me what i am doing wrong? or what is happening. Thanks in advance.
when i echo my $str i get the following:
You are passing to json_decode a string that is not valid JSON, this is the reason NULL is returned.
As I see from comments inspecting the error code generated gives 4 that corresponds to the constant JSON_ERROR_SYNTAX that just means the JSON string has a Syntax Error.
(See http://php.net/manual/en/function.json-last-error.php)
You should inspect (echo) what you get from
$str = file_get_contents('http://localhost/data.json');
(You may edit your answer and post it - or a portion of it)
For sure it is not valid JSON; the problem lies there: in data.json.
Then as you fix things and get from data.json what is expected I would ensure you really need to use html_entity_decode on the fetched data.
It would be "weird" to have html encoded JSON data.
UPDATE
Looking at what you get from data.json it seem the JSON data contains actually HTML entities (as I see the presence of s)
This is actually weird, the right thing to do would be to fix how data.json is generated ensuring non-html-encoded JSON data is returned, charset is UTF-8 and the response content type is Content-Type: application/json.
We can't deepen this here as I don't know where does data.json come from or the code that generates it. Eventually you may post another answer.
So here is a quick fix provided that the right approach would be what I just suggested above.
As you decode html entities, non breaking spaces turns into 2 byte UTF-8 characters (byte values 196, 160) that are not valid for JSON encoded data.
The idea is to remove these characters; your code becomes:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
// the character sequence for decoded HTML
$nbsp = html_entity_decode( " " );
// remove every occurrence of the character sequence
$decodedstr = str_replace( $nbsp, "", $decodedstr );
$jarray = json_decode($decodedstr, true);
from php manual
http://php.net/manual/en/function.json-decode.php
Return:
... NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit
So, surely the JSON string passed to json_decode() is not valid:
maybe because of html_entity_decode
I am trying to decode a JSON string in PHP,but somehow the json_decode doesnt like my string, i think it is not valid json. The thing that is very strange to me is, that if i put the json response in a variable manually, it is working. If i write the json response out in the browser, and i write the content of the variable, both are completely the same, like this:
{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}
If i look in the webpage source, the content is also completely the same. I have also tryed to convert to UTF8, but no change.
How do you guys usually debug this, or what did i forget ?
code:
// calling web service and saving json response in variable
$json_response = CallAPI($method, $url, $json_request);
// the response contain some unvalid character in the end, so i am removing it
$json_response = substr($json_response, 0, strpos($json_response, "}"));
// trying to decode it, IT PRINTS OUT NULL
var_dump(json_decode($json_response, true));
// copying the json response from the above and putting it into a variable
$json_response = '{"id":455433,"Created":"2016-04-30T12:55:12.313","SenderCompanyName":"x","InvoiceNumber":"2525","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
// trying to decode it, IT PRINTS OUT THE RESULT SUCCESFULLY
var_dump(json_decode($json_response, true));
Try this:
<?php
$json = '{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
var_dump(json_decode($json));
?>
I finally found the solution.
I had forget to add this in my CURL OPTIONS:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
After adding this, its working fine
I am working on web services of Android application in PHP. I am trying to send URL with other data in JSON. But the data sent by URL shows unwanted slashes (//) in the URL.
Here is the code I am using:
if(isset($_POST['category_id'])):
$result=$db->sub_category($_POST['category_id']);
if($result):
$msg="Success";
$arr = array();
while($row=mysql_fetch_array($result)):
$arr['response'][] = array('category' => $row['category'], 'image' => "http://intelmobizsolution.com/Iphone/upload/iphone/".$row['image'], 'msg'=>$msg,'status'=>true);
endwhile;
$abc=json_encode($arr);
echo json_encode($arr);
endif;
endif;
But the result shows like this:
{"response":[{"category":"Administrative Support2","image":"http:\/\/intelmobizsolution.com\/Iphone\/upload\/iphone\/27792582102banner_02.jpg","msg":"Success","status":true}]}
How can I send a URL with JSON in the format I want?
The best approach is to accept the slashes. They do absolutely not harm. It is perfectly acceptable to have them escaped in JSON strings.
If you really want to get rid of them, then you can use:
json_encode($arr, JSON_UNESCAPED_SLASHES);
… but if your data ever includes the string </script> and you output the JSON into some JavaScript in an HTML document, then you'll break your script.
In PHP > 5.4 you can use
json_encode($arr, JSON_UNESCAPED_SLASHES);
http://php.net/manual/en/function.json-encode.php
I'm trying to encode a response array as json and it has worked until now.
$response = array();
$response['icons']= $icons_arr;
$response['message']= $msg;
echo json_encode( $response );
The result is
Array{"icons":["{\r\n\t\t\t\t\t\"icon_web_id\": \t\t\t\"0 ...
Javascript throws an error as it can't parse the "Array" word. I suspect the JQuery function $.parseJSON() expects a {} or a [].
What am I doing wrong here? Why won't json_encode() function properly?
Bonus question: what is causing all these \t\t\t\t's to occur?
Some other piece of code is producing the 'Array' output before the json string is output, you can prove this by changing the output line to
echo "json_encode returned ".json_encode( $response );
Check your code for other echo statements.
Regarding your Bonus question:
The \t is a tab in PHP. Your code may contain tabs instead of spaces somewhere, which could be rendered as multiple \t's.
I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.