Quote in json data - php

Hi you can see there's quote before rural management, this is causing problem while json decoding.. how can i retrive this using PHP json_decode?
[{
"employ":{
"id":"234",
"name":""rural management"
},
"pos":{
"name":"Programme Officer"
}
}]

You can't. The data is not JSON.
You need to make sure the data is in JSON format before passing it to json_decode.
As a quick hack, you could just perform a string substitution and change "" to "\" globally, but that isn't a robust solution. There is something wrong with the underlying JSON generator that you are getting the data from and that needs to be fixed at the source (probably by switching to using a JSON library instead of smashing strings together).

Related

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

When using GET in php for data generated with jQuery's $.param(data), there are %5B and %5D

I have JSON data called rowdata that I use in an ajax call. If I use:
JSON.stringify(rowdata)
it looks like like the following:
{"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"}
I do send it to php and use a GET statement (Joomla's
JRequest::getVar("Description", "", "", "")
statement) to get the elements of rowdata but I cannot succeed.
If I look at the ajax data that has been send I do have the following:
rowdata%5BDescription%5D=qwerty
etc. after applying:
$.param(data)
I have used many version instead of "Description", but to no avail. I tried to get rowdata on its own and access its elements, but no success. I cannot find out what the %5B and %5D means, searching for that is problematic with the % sign. Anyone who can help to get the values of Description, Code, etc. in php?
You are sending JSON, but trying to parse it as application/x-www-form-urlencoded data.
Don't convert the object to JSON.
$.get('example.php', {"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"});
I believe %5B is [ and %5D is ]. Your URL is encoding special characters. It's called URL encoding.
Do not use JSON if you want to push data with get... otherwise it will be encoded to satisfy JSON format and you will get those entities.
$.get('target.php', {"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"});

Not able to parse this json

I am trying to parse the json output from
http://www.nyc.gov/portal/apps/311_contentapi/services/all.json
And my php json_decode returns a NULL
I am not sure where the issue is, I tried running a small subset of the data through JSONLint and it validated the json.
Any Ideas?
The error is in this section:
{
"id":"2002-12-05-22-24-56_000010083df0188b4001eb56",
"service_name":"Outdoor Electric System Complaint",
"expiration":"2099-12-31T00:00:00Z",
"brief_description":"Report faulty Con Edison equipment, including dangling or corroded power lines or "hot spots.""
}
See where it says "hot spots." in an already quoted string. Those "'s should've been escaped. Since you don't have access to edit the JSON perhaps you could do a search for "hot spots."" and replace it with \"hot spots.\"" like str_replace('"hot spots.""', '\\"hot spots.\\""\, $str); for as long as that's in there. Of course that only helps if this is a one time thing. If the site continues to make errors in their JSON output you'll have to come up with something more complex.
What I did to identify the errors in the JSON ...
Since faulty quoting is the first thing to look for, I downloaded the JSON to a text file, opened in a text editor (I used vim but any full featured editor would do), ran a search and replace that removed all characters except double-quote and looked at the result. It was clear that correct lines should have 4 double-quotes so I simply searched for 5 double-quotes together and found the first bad line. I noted the line number and then undid the search and replace to get the original file back and looked at that line. This gives you what you need to get the developers of the API to fix the JSON.
Writing code to automatically fix the bad JSON before giving it to json_decode() would be quite a bit harder but doable using techniques like those in another answer.
According to the PHP manual:
In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
Try calling it to see where the error is.

What JSON does this CF code return?

Trying to implement the excellent jQuery bidirectional infite scroll as explained here:
http://www.bennadel.com/blog/1803-Creating-A-Bidirectional-Infinite-Scroll-Page-With-jQuery-And-ColdFusion.htm
For the server-side, which returns JSON, the example is in ColdFusion. Trying to implement it in PHP.
I need to find out what the format of the JSON is.
RIght now, I am returning
[{"src":"https:\/\/s3.amazonaws.com\/gbblr_2\/100\/IMG_1400 - original.jpg","offset":"5"},{"src":"https:\/\/s3.amazonaws.com\/gbblr_2\/100\/IMG_1399 - original.jpg","offset":6},{"src":"https:\/\/s3.amazonaws.com\/gbblr_2\/100\/IMG_1398 - original.jpg","offset":7}]
which doesn't work, in the html that is generated it shows "UNDEFINED" for both the src and the offset variables.
So my question: what kind of JSON does that coldfusion code generate? What is the format of JSON that I need to return.
Thanks for any tips!!
CF's JSON mentioned in Ben's post is similar to this:
[{"SRC":"http:\/\/example.com\/public","OFFSET":3.0},{"SRC":"http:\/\/example.com\/public","OFFSET":3.0}]
I'd try to check key names first. Yes, CF makes them uppercase, and JS doesn't like it sometimes. Check his function applyListItems() and check if RegExp finds something or not.
If this doesn't help little Firebug line debugging and console.log will do the trick I guess.
Looks like the JSON you're creating should be equivalent to his. He is creating an array of structures; where each structure contains the keys "src" and "offset".
He is converting to base64 and binary for streaming purposes, but I don't know how that would work -- or if it would be required -- for a php implementation.
I would use Firebug to figure out exactly where in your JavaScript the error is being thrown. That will tell you more about what exactly the problem is.

mySql table returning JSON that needs formatting for a iPhone UITableview

I have a php query the returns the following JSON format from a table.
[{"memberid":"18",
"useridFK":"30",
"loginName":"Johnson",
"name":"Frank",
"age":"23",
"place":"School",
},
It needs the following format:
[{"memberid":"18" {
"useridFK":"30",
"loginName":"Johnson",
"name":"Frank",
"age":"23",
"place":"School",}
},
I can figure out where/how to convert this, Where would I create the formatting following:
(1) In the php return?
(2) the JSON instructions for deserialization?
or (3) Some kinb of Obj-C coding instruction?
My end use is a simple Drill Down table using the NSObject, so when I select "memberid" row, I'll get the child/detail list on the next UITableview.
My Data.plist will look like the following:
Root: Dictionary
V Rows: Array
V Item 0: Dictionary
Title: String 18
V Children Array
V Item 0 Dictionary
Title String 30
etc.
Thanks in advance, this site rocks.
I'm sure its just a typo, but for starters ->
[{"memberid":"18" {
"useridFK":"30",
"loginName":"Johnson",
"name":"Frank",
"age":"23",
"place":"School",}
},
is not valid, there needs to be a comma after the "18"
Anyway, it is easier to fix the php to output the JSON you want than it is to re-organize it in Objective-C. Once you actually have the JSON from the response, you will either need to parse it manually, which isn't too bad, or use a library (a la http://code.google.com/p/json-framework/ ).
Most communications on the iPhone are done with NSXMLParser or libXML instead of JSON. Both routes are equally hairy as the iPhone deals best with a recursive event-driven XML parser (which most people are unfamiliar with), and does not have native support for JSON (which is by far easier to read).
If JSON isn't working out for you and you end up moving to XML, look up event-driven parsing, its a bit of work to setup, but very fast once its actually running.

Categories