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
Related
I want to use json_decode() to decode a string stored in a database like this:
{"results":[{"r":"1","c":"0"},{"r":"2","c":"0"},{"r":"3","c":"0"}]}
The problem is: the function returns NULL.
But when I try the following code, everything works:
$data ='{"results":[{"r":"1","c":"0"},{"r":"2","c":"0"},{"r":"3","c":"0"}]}';
$JO=json_decode($data);
var_dump($JO);
The value returned from the database is exactly the same as I described above.
For all the people who might get the same problem, my problem was that when I was getting data from database to display it, I was adding html style and table parameters to the data, after removing them everything went back to normal.
I'm writing PHP code that uses a database. To do so, I use an array as a hash-map.
Every time content is added or removed from my DB, I save it to file.
I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).
I built two functions:
function saveDB($db){
$json_db = json_encode($db);
file_put_contents("wordsDB.json", $json_db);
} // saveDB
function loadDB(){
$json_db = file_get_contents("wordsDB.json");
return json_decode($json_db, true);
} // loadDB
When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).
The json string itself is very long (~200,000 characters, and that's just for testing).
I tried the following:
Replacing single/double-quotes with double/single-quotes (Without any backslashes, with one backslash and three backslashes. And any combination I could think of with a different number of backslashes in the original and replaced string), both manually and using str_replace().
Adding quotes before and after the json string.
Changing the page's encoding.
Decoding without saving to file (Right after encoding).
Checked for slashes and backslashes. None to be found.
Tried addslashes().
Tried using various "Escape String" variants.
json_last_error() doesn't work. I get no error number (Get null, not 0).
It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.
I believe the size has something to do with it, because small strings seem to work fine.
Thanks Everybody :)
In your JSON file change null to "null" and it will solve the problem.
Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.
EDIT:
After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:
"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":
Change that null to be valid property name and json_decode will do the job.
I had a similar problem last week. my json was valid according to jsonlint.com.
My json string contained a # and a & and those two made json_decode fail and return null.
by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.
I suggest var_dumping and using find dunction to look for these king of characters.
Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.
Kickself #124
I have a json_encoded array which is fine.
I need to strip the double-quotes on all of the keys of the json string on returning it from a function call.
How would I go about doing this and returning it successfully?
Thanks!
I do apologise, here is a snippet of the json code:
{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}
Just to add a little more info:
I will be retrieving the JSON via an AJAX request, so if it would be easier, I am open to ideas in how to do this on the javascript side.
EDITED as per anubhava's comment
$str = '{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}';
$str = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $str);
echo $str;
This certainly works for the above string, although there maybe some edge cases that I haven't thought of for which this will not work. Whether this will suit your purposes depends on how static the format of the string and the elements/values it contains will be.
TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
DETAILS:
A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
In my case I saw the difference using Chrome's debugging tools. When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger. This allowed the object to be immediately treated as an object without using a JSON.parse() call. Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys. This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type. I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required. Now I can switch between the legacy and new system without any changes except the destination URL.
For some reason json_decode is returning NULL with valid JSON.
The json is located here: http://www.nfl.com/liveupdate/scorestrip/scorestrip.json
I am getting the file contents of the page (file_get_contents) and then running json_decode on it.
Also tried stripslashes b/c of magic quotes.
Thanks in advance,
Phil
$json = file_get_contents('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json');
var_dump(json_decode($json));
The empty array elements are invalid JSON, ie the multiple commas with no values between
["Thu","7:30","Final",,"BAL","6","PHI","13",,,"55424",,"PRE1","2011"]
^ Here ^ Here ^Here
You could try inserting empty strings between multiple commas (thanks hakre), ie
$json = preg_replace('/,(?=,)/m', ',""', $json);
// I'm dubious about this working, don't have PHP to test but it works in JS
I don't know if this messes up your ability to continue using the data though
I came the same conclusion as Phil, but it took me about 5 minutes longer. : )
However, I noticed a problem in his output... it is dropping a field.
I don't like doing this kind of pattern detection in RegEx, only because I think it is harder to maintain. In this case, I just run it through a while loop.
while (strpos($json,',,'))
{
$json = str_replace(',,',',"",', $json);
}
I'm sure Phil can come up with a proper RegEx, but this solution will maintain the right # of entries & their ordinal positions.
For anyone looking in 2014. The new feed data link should be:
http://www.nfl.com/liveupdate/scores/scores.json
I'm playing with the flickr api and php. I want to pass some information from PHP to Javascript through Ajax. I have the following code:
json_encode($pics);
which results in the following example JSON string:
[{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}]
Javascript has problems with this, however, due to the unescaped single-quote in the second item ("can't deny").
I want to use the function json_encode with the options parameter to make it strip the quotes, but that's only available in PHP 5.3, and I'm running 5.2 (not my server). Is there a fast way to run through the entire array and escape everything before encoding it in Json? I looked for a way to do this, but it all seems to deal with encoding it as the data is generated, something I cannot do as I'm not the one generating the data.
If it helps, I'm currently using the following javascript after the ajax request:
var photos = eval('(' + resptxt + ')');
Have you considered using JSON2 instead of eval()? Details here.
str_replace('\'', '\\'', json_encode($pics))
You'll have to do a (recursive) foreach to walk through the array and manipulate them manually. You can do a str_replace, but addslashes works just as fine (and addcslashes is even better.)