Jump to content

json_decode and line breaks


fivestringsurf

Recommended Posts

php5

I am using json_encode() to store an array of data as a string in a mysql data base.

I then extract the sting from the data base  and convert the back into an array using json_decode.

 

This works great up until I have any line breaks in any of the data.

When there is a line break, the json_decode() function chokes and returns nothing.

 

I would really like to keep the line breaks.

 

Has anyone come across this issue/have an suggestions/solutions?

Link to comment
https://forums.phpfreaks.com/topic/245543-json_decode-and-line-breaks/
Share on other sites

Having a literal line-break (i.e. not just written as "\n") is not valid within JavaScript, and JSON is based on JavaScript so I imagine the same rules apply. For example, this is not allowed:

 

var foo = "
    some text here
    more text here
";

 

But this is:

 

var foo = "\nsome text here\nmore text here\n";

 

You may be better off using serialize if this only used in PHP. It results in a larger string, but will work with your line breaks.

@Adam

good suggestion...that was my first implementation, I was just trying to cut down on size/clutter and thought json was nice and tidy.  I guess I'll just go back to serialize. 

 

What's strange though... In past projects, I seem to remember passing tons of json encoded strings back to html for ajax updates, and unless my memory is failing (which it probably is) there were line breaks in the data.

running the test like on the data coming from the db results in:

"- Syntax error, malformed JSON"

 

it's definitely the line breaks causeing the issue

 

Come to think of if, maybe I wasn't using line breakes in the past, probably break tags and html tags to handle line breaks on screen.

I'll just stick to serialize()

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.