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.
Related
I made a post in a form converting my javascript localstorage to a post request. From there I tried to decode my json string to make an object in PHP.
How my php code looks before I echo it
$cart_items = $_POST['cart_items'];
$cart_items = json_encode($cart_items);
$array_test = json_decode($cart_items);
print_r($array_test);
What it returns in browser
[{\"id\":83494890,\"title\":\"2020 Hino 358\",\"partType\":\"Bumpers\",\"price\":100,\"stockNumber\":12313131312,\"thumbImg\":\"/jOIY91KhEby8_f.jpg\",\"permalink\":\"/part-description/?part=83494890\",\"maxQuantity\":1,\"requestedQuantity\":\"3\"}
,{\"id\":83493833,\"title\":\"2009 Freightliner 5020080\",\"partType\":\"ABS Modulator Valves\",\"price\":150,\"stockNumber\":\"P-1211111111157\",\"thumbImg\":\"/OOjQbsi6p8kX_f.jpg\",\"permalink\":\"/part-description/?part=83493833\",\"maxQuantity\":1,\"requestedQuantity\":\"1\"}]
I know that typically when seeing json data there isn't forward slashes everywhere. I tried to json_decode into an array rather than an object, then make a foreach for each object inside. But I got this error returned "Invalid argument supplied for foreach()"
How do I make this json string convert to an array of objects? Thank you
The problem I was having was when I was getting the $_POST[] it was using PHP's "magic quotes" which was giving me improper format for my json. That being said, after disabling this, it removes the slashes.
It looks like $_POST['cart_items'] already contains JSON. So you just need to decode it, not encode it first.
$array_test = json_decode($_POST['cart_items'], true);
print_r($array_test);
But it's actually encoded twice, that's why it has escaped quotes, so you need to call json_decode() twice. But it's missing the double quotes around the whole thing, and the embedded newline is not valid.
The following works:
<?php
$cart_items = '"[{\"id\":83494890,\"title\":\"2020 Hino 358\",\"partType\":\"Bumpers\",\"price\":100,\"stockNumber\":12313131312,\"thumbImg\":\"/jOIY91KhEby8_f.jpg\",\"permalink\":\"/part-description/?part=83494890\",\"maxQuantity\":1,\"requestedQuantity\":\"3\"},{\"id\":83493833,\"title\":\"2009 Freightliner 5020080\",\"partType\":\"ABS Modulator Valves\",\"price\":150,\"stockNumber\":\"P-1211111111157\",\"thumbImg\":\"/OOjQbsi6p8kX_f.jpg\",\"permalink\":\"/part-description/?part=83493833\",\"maxQuantity\":1,\"requestedQuantity\":\"1\"}]"';
$array_test = json_decode(json_decode($cart_items));
print_r($array_test);
I suggest you find the code that's sending the cart_item POST parameter and fix it so it doesn't do all this extra encoding.
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;
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 try to create a script that decoding a simple JSON string in PHP and I get the following error:
quoted object property name expected
The string I try to decode is the following :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
and the code I use to decoded is the following:
json_decode( $json_string );
I also have try to validate my json string in some online json validators, and the string seems to be fine.
Can someone please help me ?
Do you think the problem exists because of the double quotes ?
Update #1
Definetelly was a debuging issue. I place my experience here just to help other devs may come accross the same issue in the feature:
The problem was that my variable that came with the json string was html encoded so instead of the following string :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
my variable came with the following string inside :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
The mistake by my side was that I used the print_r method instead of the var_dump . This had as a result to print out the " as " in my page .
The json string is valid, and it works. You can add true for the second parameter of json_decode, and you get back an array.
Try the following:
$json_string = '{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}';
var_dump(json_decode($json_string, true));
It works for me.
I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:
<?php
header('content-type: application/json; charset=utf-8');
if( strlen($_GET["feed"]) >= 13 ) {
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml) {
$data = #simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
}
}
?>
The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..
Is there a way I can change these characters prior to sending back or pass json_encode options?
You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):
$json = json_encode(array($data));
EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.
You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).
SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:
$json = json_encode(array($data));
We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..
It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?