PHP Json Encoding w/ quote escaping in 5.2? - php

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.)

Related

Remove double-quotes from a json_encoded string on the keys

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.

json_decode returns null with PHP, NFL API

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

mysql_real_escape_string() -> stripslashes() -> jquery.append()

im letting my users type in texts, then take them to server side php and process them, and if everything goes as it should, i just append the text with jquery without the page having to load all over again.
This is the procedure:
$post_text = htmlspecialchars(mysql_real_escape_string($_POST['post_text']));
some logic...
everything ok!
stripslashes(str_replace("\\n", "", $post_text))
and then i send all the nessesary data witj json
echo json_encode($return);
on the client side i append the html chunk saved in a variable from the server side.
this seems to work on localhost, it removes all the slashes and so on, but online it just doenst remove the slashes, and they keep coming up, when i hit refresh they dissapear becouse then its a
stripslashes($comment['statusmsg_text'])
written out with php straight from the database. Is it the json that adds some extra stuff? i dont get it becouse it works perfectly on localhost.
best of regards,
alexander
The additional slashes might be magic quotes. You shouldn’t rely on them and disable them.
Additionally, mysql_real_escape_string should only be used to prepare strings to be put into a string context in an MySQL statement. Similar applies to htmlspecialchars that should only be used for sanitizing data to be put into an HTML context.
It may be, that on your server and your localhost the magic_quotes_gpc directive is set differently, so your string is double encoded on server side.
Try it without stripslashes, json_encode should handle that. All you need to do is use mysql_real_escape once, before your string touches your database.

Single quotes in JSON from PHP causing problems

NOTE: this was a completely different question until I realized where the problem really was.
My current issue is that I am trying to output some JSON from PHP for use by jQuery. I am doing this cross-domain so I am using "JSONP". I have narrowed the problem down to the fact that there are single quotes in my JSON so when I output with the callback function I end up getting too many single quotes.
I have tried calling str_replace("'","\'",$value) in PHP and it seems to output as \\' in my JSON rather than \' which is apparently not readable by jQuery (though online JSON validators say the JSON is valid.
So what I need to know is how to get only a single slash in my string inside of PHP rather than 2 slashes.
What I'm gathering is this:
jQuery uses _ as a callback parameter to JSONP requests. It will automatically append ?_=jQuery<random_numbers> basically telling the server to call this unique function name when it returns. As such, as of recently (within the last year I want to say) .ajax takes care of making a callback function for you, then kind of "re-routes" it to a function you specify within the success property.
Also, your PHP code is using $_GET['callback'] when it now should be using $_GET['_'] (to stay more in-line with jQuery and what it's sending).
The "jQuery was not called" is just jQuery notifying you that anticipated callback wasn't included in the response, and it was looking to make sure it was getting called.
Short answer (as I see it) reference $_GET['_'] instead of $_GET['callback'] to satisfy jQuery.
try to use this in your PHP:
echo $_GET['callback'] . '(' . json_encode($your_array_data) . ')';
Regards.

Clean php output into javascript

Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php

Categories