Remove double-quotes from a json_encoded string on the keys - php

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.

Related

JSON with Variable At Beginning?

I am loading an external JSON file. Which seems to load fine. Im using this script to load it:
$file ="https://creator.zoho.com/api/json/los/view/All_clients?
authtoken=xxx";
$bors = file_get_contents($file);
When i dump the results, I get:
string(505) "var zohoappview55 = {"Borrowers":[{"Full_Name":"Mike Smith","Email":"dadf#gmail.com","Address":"111 S. Street Ct., Aurora, CO, 80012","Position":"Borrower","ID":"1159827000004784102","Mobile":"+13033324675","Application":"Application 1 - 1159827000004784096"},{"Full_Name":"Stacy Smith","Email":"sdfa#gmail.com","Address":"111 S. Street, 80012","Position":"Co-Borrower","ID":"1159827000004784108","Mobile":"+1303558977","Application":"Application 1 - 1159827000004784096"}]};"
Looks like the json has a predefined var zohoappview55 at the begining of the json. Not sure if this is my issue but when i use json_decode it doesn't not decode. If i remove this beginning variable it decodes just fine.
i don't have a way to change this variable or edit the json file as it's a remote file. Does anyone know how to decode it in the native format with the variable at the beginning?
Having a quick look through the API documentation of zoho, it seems it should normally return correct json. It may think that it's a browser requesting the file as a javascript source so you may need to add an Accept header to your request.
This cannot be done with file_get_contents so you will probably need to use curl instead.
Try to perform a normal php curl request with the header Accept: application/json.
See: PHP cURL custom headers for reference.
But as Alex Howansky said in the comment. The API might not be intended for that. In that case you will need to strip the beginning and end of the received document.

PHP json_decode returns null

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

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.

Why doesn't jQuery.parseJSON() work on all servers?

Hey there, I have an Arabic contact script that uses Ajax to retrieve a response from the server after filling the form.
On some apache servers, jQuery.parseJSON() throws an invalid json excepion for the same json it parses perfectly on other servers. This exception is thrown only on chrome and IE.
The json content gets encoded using php's json_encode() function. I tried sending the correct header with the json data and setting the unicode to utf-8, but that didn't help.
This is one of the json responses I try to parse (removed the second part of if because it's long):
{"pageTitle":"\u062e\u0637\u0623 \u0639\u0646\u062f \u0627\u0644\u0625\u0631\u0633\u0627\u0644 !"}
Note: This language of this data is Arabic, that's why it looks like this after being parsed with php's json_encode().
You can try to make a request in the examples given down and look at the full response data using firebug or webkit developer tools. The response passes jsonlint!
Finally, I have two urls using the same version of the script, try to browse them using chrome or IE to see the error in the broken example.
The working example : http://namodg.com/n/
The broken example: http://www.mt-is.co.cc/my/call-me/
Updated: To clarify more, I would like to note that I manged to fix this by using the old eval() to parse the content, I released another version with this fix, it was like this:
// Parse the JSON data
try
{
// Use jquery's default parser
data = $.parseJSON(data);
}
catch(e)
{
/*
* Fix a bug where strange unicode chars in the json data makes the jQuery
* parseJSON() throw an error (only on some servers), by using the old eval() - slower though!
*/
data = eval( "(" + data + ")" );
}
I still want to know if this is a bug in jquery's parseJSON() method, so that I can report it to them.
Found the problem! It was very hard to notice, but I saw something funny about that opening brace... there seemed to be a couple of little dots near it. I used this JavaScript bookmarklet to find out what it was:
javascript:window.location='http://www.google.com/search?q=u+'+('000'+prompt('String?').charCodeAt(prompt('Index?')).toString(16)).slice(-4)
I got the results page. Guess what the problem is! There is an invisible character, repeated twice actually, at the beginning of your output. The zero width non-breaking space is also called the Unicode byte order mark (BOM). It is the reason why jQuery is rejecting your otherwise valid JSON and why pasting the JSON into JSONLint mysteriously works (depending on how you do it).
One way to get this unwanted character into your output is to save your PHP files using Windows Notepad in UTF-8 mode! If this is what you are doing, get another text editor such as Notepad++. Resave all your PHP files without the BOM to fix your problem.
Step 1: Set up Notepad++ to encode files in UTF-8 without BOM by default.
Step 2: Open each existing PHP file, change the Encoding setting, and resave it.
You should try using json2.js (it's on https://github.com/douglascrockford/JSON-js)
Even John Resig (creator of jQuery) says you should:
This version of JSON.js is highly recommended. If you're still using the old version, please please upgrade (this one, undoubtedly, cause less issues than the previous one).
http://ejohn.org/blog/the-state-of-json/
I don't see anything related to parseJSON()
The only difference I see is that in the working example a session-cookie is set(guess it is needed for the "captcha", the mathematical calculation), in the other example no session-cookie is set. So maybe the comparision of the calculation-result fails without the session-cookie.

PHP Json Encoding w/ quote escaping in 5.2?

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

Categories