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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.