I have a data i want to json_decode, the data was json_stringify before being sent to PHP and the data looks like this:
{\"data\":{\"buildingID\":{\"2\":{\"path\":[[11,11],[10,11],[10,10],[9,10],[8,10],[8,9],[8,8],[8,7],[8,6]]}}}}
In my script i have:
echo $_GET['as']; //this is what you see above^
$obj = json_decode($_GET['as']);
echo $obj; //no output
var_dump($obj); //this shows NULL
There are also no errors/notices/warnings in my error logs either.
I'm wondering if the slashes is causing some kind of problem ?
The slashes are indeed the problem.
My guess is that magic quotes are the culprit. I suggest you disable magic quotes.
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 am creating an array of pages using the following query:
$pages = Page::orderBy('sorting')->get()->toArray();
When I then json_encode the output, the output is corrupted when one of the page titles has a quote in it. How can I prevent this?
If you want to return json, you should use:
$pages = Page::orderBy('sorting')->get()->toArray();
return response()->json(['pages' => $pages]);
it should not make any problems. In case you have any, please show what they are.
I've experienced problems with json only when I have DB connection non-UTF and have their some characters. As json_encode needs data be in UTF-8 it might cause problems
Laravel is indeed returning a correct JSON. It seemed the javascript needed to call the object in a weird style, where the object needed to be placed within single quotes: UINestable.init('{ $json) !!}'). So when a single quote was within the JSON it would fault. Thanx though
I normally find my answers through searches, but this ones got me stumped and I can't find any related articles :/
I am simply running an AJAX call to my PHP script and alerting the returned value (JSON encoded object).
The problem is, the script freezes as soon as it hits my 'echo' statement. I have tested without the echo, and even with values such as "Hello" (both which were successful). I also tested an output with an example JSON string that I found online. This failed.
I am now believing that any string structured as JSON will cause this error (I have tested both JSON scripts on jsonlint.com).
All help is greatly appreciated!!!
Javascript Code:
function scan()
{
var script = "../resources/ajax/fincenmanager/load_reports.php";
var params = "";
var return_function = "load_wire";
document.getElementById("loading_screen").className = "show";
ajax(script, params, return_function);
}
function load_wire(text)
{
document.getElementById("loading_screen").className = "hidden";
alert(text);
}
PHP Code:
<?php
require_once("../../config.php");
require_once("../../library/FincenManager/fincenmanagerclass.php");
header("Content-Type: application/json");
$manager = new FincenManager("../../inputs/FincenManager/");
$json = json_encode($manager);
// Script Breaks After This Line.. 100% Sure :/
echo $json;
?>
You need to ecape a lot more then just the " character (as you discovered).
In this case, the problem is that the " ends the string and JSON is not expecting a character after the " but a ,, ] or an } there.
The answer of this question will help you further with the escaping of the characters: click
And for testing JSON: JSONlint
Well,
I am looking into reasoning but I believe this should be sufficient to help anyone who runs into this problem:
The double quotes in my JSON string (the double quotes created by json_encode when encoding the object) were causing the 'echo' statement to fail. To resolve this I replaced all unescaped double quotes with escaped double quotes using the following:
str_replace( " \" " , " \\\" " , json_encode($object) )
I believe this to be the result of json_encode not escaping the double quotes on its own, and only happens when trying to 'echo' from an external script called from an ajax request.
Thanks Everyone :D
Okay so I have a php script and I need to somehow view the value of one of my variables. The thing is this variable is a very long string of XML that got returned from a server. I know it has an error message in it but I need to actually see what it is saying. If I try and Print or echo the value it only displays part followed by a ... or if I use var_dump it does the same. I've even gone as far as trying to echo a javascript alert with the value but that fails because there are single and double quotes in the xml causing the alert quotes not to be recognized correctly. I just need to see the value of this variable. Any advice? Thanks.
Edit:
Actually said that wrong. Echo and print don't display the value correctly because the tags are in <> brackets so it is recognizing as an html tag.
You can use htmlentities to output the XML string so that you can get a plaintext view of it in a browser.
<?php echo htmlentities( $xml_string); ?>
Alternatively, you can parse the XML string to reveal the error message, but this may be more complicated than what you need.
Try echo htmlentities($var, ENT_COMPAT, 'UTF-8')
i always use this:
echo "<pre>". htmlentities($s) . "</pre>";
Try this:
echo '<pre>'.$xml_string.'</pre>';
See also:
CDATA - (Unparsed) Character Data
i usaly use:
echo nl2br(str_replace('<', '<', $xml));
as its only the < that are a problem
You could just save the XML string to a file. If it's well-formed XML, you can view it with every browser (and expand/collapse nodes ^^).
I've been going bananas trying to get some data from Javascript on one page to post to a php file asynchronously. I'm not even attempting to do anything with the data, just a var_dump to spit back out from the ajax call. NULL over and over again.
I've checked the JSON with JSONLint and it validates just fine. I'm getting my JSON from JSON.stringify - Firebug tells me I'm getting the following:
{"items":[["sa1074","1060"],["sa1075","1061"]]}
I've tried php://input, as well as json_decode_nice from the PHP manual comments about the function, and I've tried using utf8_encode - is there something wrong with my JSON?
EDIT: Derpity dee probably should have planned this post a bit more haha. Here's my PHP (using a suggestion from PHP manual comments)
function json_decode_nice($json, $assoc = FALSE){
$json = str_replace(array("\n","\r"),"",$json);
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
return json_decode($json,$assoc);
}
if (isset($_POST['build'])){
$kit = file_get_contents('php://input');
var_dump(json_decode_nice($kit));
}
And the JS used to create it:
var jsonKit = JSON.stringify(kit);
$.post("kits.php?", {"build" : jsonKit},
function(data) {
$("#kitItems").html(data);
});
Also: Our host is on PHP 5.2 - I found this out when I uploaded a perfectly good redbean class only to have it explode. Had to re-implement with legacy redbean. Our host is busted.
SOLVED: Thanks to all who commented. Didn't think to check $_POST to see what was coming in. Quotes were being escaped with slashes in the $_POST and json_decode was choking on it. Adding this line before decoding solved the problem. Also forgot to set true to return an associative array. Thanks!
$kit = str_replace('\\', '', $kit);
Without seeing code - I'm just guessing here ... are you using a true assoc variable in your json_decode()?
<?php json_decode($jsonString, true); ?>
That had me stumped on a decode for quite some time my first time trying to decode something,