PHP Json Malformed When Posted From jQuery Ajax - php

I am having a weird issue, when i use json_decode() on some json from a jquery ajax call it's coming back always saying that the json is malformed (JSON_ERROR_SYNTAX).
I say this is weird because if i take a copy of the raw posted json from the developer console and manually push it through json_decode() then it decodes perfectly fine.
I have uploaded a txt file of the example json here : https://drive.google.com/file/d/1IZ5RkpFK7KLUNYeZe4dPdxGWZXinmFSJ/view?usp=sharing which works manually parsing it but not from posted data. Another weird issue is if i save the json string to a longtext field in a mysql database and then pull it out again, it then decodes fine; but this isn't ideal, it needs to validate it before going to the database and i'm unsure why this would allow it to decode anyway.
Any ideas?

This might be happeing due to new line code added in your code. You can add below code and try to decode the code again it might work.
$content = preg_replace('/[\r\n\t\s]+/s', ' ', $content);#new lines, multiple spaces/tabs/newlines
$content = preg_replace('#/\*.*?\*/#', '', $content);#comments
$content = preg_replace('/^\s+/', '', $content);#spaces on the begining

Related

PHP: Merge multiple JSON encoded lines

When users keep interacting with my web app, the pages keep doing calls so that some info can be stored in a cookie linked file that is stored on the server (with the PHP session file, it gets complex: I don't have choice to see a complete history, etc.)
So, anyway, with every ajax call, I create json_encoded data in a flat file with the unique cookie name.
Data example of one such cookie file: (keys/values may repeat)
{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}
Now, when I am searching this file, to retrieve data and to do other stuff, I would like to have the entire contents in one big array as if the entire data ws json_encoded in one shot.
How do I do this? I could do a bunch of str_replace and replace the "{" and "}" and get rid of the carriage returns but that seems to be a bit ugly
Is there a better way?
Thanks
I suggest to fix your json format by using str_replace as you saying because this is the only way to have a valid json format on using this function:
$str = '{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}';
$fix_json = "[" . str_replace("}\n{", "},{", $str) . "]";
and after this you can decode you json and convert it with json_decode, like this:
$dataArray = json_decode($fix_json, true);

How to properly store CKEditor HTML input

Im using CKEditor to store HTML input. Its working fine the one way. Data goes into the database exactly as I input it.
However, when I try to retrieve it in JSON, I get all sorts of parsing errors.
Here is a simple string which screws up
<p>This is my text</p>
<span style="font-size:14px">More test</span>
The JSON gets hung up on the double quotes, and the spaces. So I implemented this function in PHP before it gets inserted.
function parseline($string){
$string = str_replace(chr(10), "//n", $string);
$string = str_replace(chr(13), "//n", $string);
$string = str_replace(chr(34), "'", $string);
$string = str_replace("'","\'", $string);
return $string;
}
That line then becomes
<p>This is a test and more content</p>//n<span style=\'font-size:72px\'>
However. This still hangs up the JSON parsing.
How do I correctly store data from CKEditor, and then how to parse it back from the database, so that it can be parsed correctly as JSON??
Ideally I want to store it properly. And then I'll need to reverse parse the //n out to display back in the editor properly. Because right now, if I get valid data, I still get the //n displayed in the editor as actual values.
Ive been on this for 6 hours now. And Im tearing my hair out.
EDIT - Still stuck on this 22 hours later
Here is what is going into the database
<p>qweqweqweqwe</p>
And then Im getting it like this (using Lumen/laravel)
$post = Post::find($id);
return json_encode($post);
Then in Vue Im getting that json
el:'#app',
data : {
post: {}
},
methods: {
getPost: function(id){
var that = this;
$.ajax({
url:'post/'+id,
dataType:'json',
type:'GET'
}).done(function(data){
// Assign the data to Vue
that.post = JSON.parse(data);
}).fail(function(xhr){
});
}
}
This fails, with this exception
Uncaught SyntaxError: Unexpected token
in JSON at position 175
And the json returned is
{"uuid":"0bcb9c59-19da-4dcf-90d6-6dd53adfb449","title":"test","slug":"test","body":"<p>qweqweqweqwe</p>
","created_at":1519529598,"updated_at":1519534639}
So obviously its failing because there is an Enter key after the ending < /p >. But I already tried removing all enter keys and all that before storing. Replacing with new line /n. That works, but then I get //n back, and also things like style="font-size:14px;" from CKeditor, also make it fail, because of the double quotes.
So the issue is. Im storing the data exactly as its entered in the database. Retrieving it properly is just most definitely not working or easy to do at all it seems. At least as valid json.
EDIT 3 - Completeley lost and officially stumped
Im getting this back as json
var data = {
"uuid": "2cd2d954-233a-46d6-8111-29596262d3bc",
"body": "<p>test<\/p>\n",
"cover_img": "https:\/\/static.pexels.com\/photos\/170811\/pexels-photo-170811.jpeg",
"title": "asdf",
"slug": "asdf",
"created_at": 1519536364,
"updated_at": 1519538302
}
If i do
JSON.parse(data);
I consistently get
Uncaught SyntaxError: Unexpected token
in JSON at position 66
Even though if you copy that exact object over to JSONLint.com, its completely valid. Im so stumped. The most stumped I think I have ever been on any issue in my entire career. Which is wierd, because it seems like it would be such an easy bug to find.
Store it directly as HTML in the database. Don't modify, tweak, or otherwise screw with it at all - what's in the database should be exactly what the user submitted. (Stuff like XSS protection, parsing short codes, etc. should be done on display, so you can adjust your algorithms while still having the original HTML to work with.)
Provide it to Vue by running it through json_encode, which will escape it correctly:
$response = ['html' => $html];
return json_encode($response);
(You can also just do json_encode($html), which will return a JS-friendly string instead of a JSON object. Vue'll be happy with that, too.)
The resulting JSON will be:
{"html":"<p>This is my text<\/p>\n\n<span style=\"font-size:14px\">More test<\/span>"}
which Vue will be just fine with when you JSON.parse it.
Assuming a CKEditor instance named editor1, get CKEditor data, construct an object with it, stringify it and send it to database without PHP manipulation (JSON.stringify will take care of escaping characters):
JSON.stringify({'ckdata': editor1.getData()})
Retrieve data from database as text without PHP manipulation and parse it as JSON object:
JSON.parse(databasedata).ckdata;
EDIT: ceejayoz gave a better answer, since data is stored unmodified in database

Read json data from Android with php

I'm trying to read data from a decompiled application of Android with a php server. I used wireshark to understand what types of data the application sends, and the result is:
{"initType":"first time","parameters":true,"details":................}
I trying to capture this data and insert them in a file with this php code:
<?php
$json = $_POST["initType"];
$decoded = json_decode($json, TRUE);
if ($decoded === FALSE) {
throw new Exception('Bad JSON format.');
}
$file_handle = fopen('tmp.json', 'w');
fwrite($file_handle, $decoded);
fclose($file_handle);
?>
The file is correctly generated but it's empty. What is the error?
Because $decoded is an array, use a loop to write it to file or write the encoded JSON to file ($json). Try using this:
fwrite('tmp.json', print_r($decoded, TRUE));
or:
file_put_contents('tmp.json', print_r($decoded, TRUE));
Update (per your comments):
If you run a print_r($decoded) and it prints nothing, there is a problem with the decoding process of the JSON object passed in. I would recommend checking this to make sure it is formatted correctly. JSON formatting is a strict business and will halt your end goal if you are missing a double-quote or bracket. Start by echoing out $json ($_POST["initType"]) and compare the format to examples posted online (just Google "json formatting"). I can tell you that one thing that stands out to me is: "parameters":true (from your example above). I have a strong suspicion that the key true should be in double quotes. If you are positive that the JSON variable is correct syntactically, I don't think I would be of any more help. Using json_decode() to produce an array to very straight forward once you get it right.
Don't decode the json at all -this only brings the problem of trying to serialize an array that burmat mentioned in his answer.
Write to the file the json content straight away:
fwrite($file_handle, $json);
Also, though I am not PHP expert it seems you access the body of the post request wrongly. Please refer to the following post.

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 from Javascript not decoding in PHP

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,

Categories