JSON: Unterminated String Literal Error

Posted March 2, 2007 at 7:21 AM by Ben Nadel

Tags: ColdFusion, Javascript / DHTML, AJAX

I was just fooling around with some JSON (JavaScript Object Notation) and kept this error whenever I tried to return a string value that contained line breaks:

"unterminated string literal"

I know what the error was (especially as FireFox's FireBug kicks sooo much butt with AJAX), but I couldn't understand how to get around it. Is it possible that JSON values cannot have line breaks? Then it hit me! Javascript line breaks are represented by the "\n" character, NOT an actual line break. Therefore, values such as:

"Libby was this really cute
trainer that I used to work
with."

... should actually be:

"Libby was this really cute\ntrainer that I used to work\nwith."

I was able to update my ColdFusion to JSON algorithm, specifically my StringToJSON() UDF to escape all the special characters:

  • <!--- Return a string object. --->
  • <cfreturn (
  • """" &
  • ToString( ARGUMENTS.Data ).ReplaceAll(
  • "(['""\\\/\n\r\t]{1})",
  • "\\$1"
  • ) &
  • """"
  • ) />

Now, it works just fine. This AJAX and JSON stuff is very cool and much more fun once you get a better idea of how it is all working.




Reader Comments

Mar 2, 2007 at 8:27 AM // reply »
33 Comments

Hey Ben, I don't know if you've ever seen it or care for it, but there's a ColdFusion implementation of JSON called CFJSON that I'm now maintaining. You can see it at http://www.epiphantastic.com/cfjson/ . I'm actually planning to release an update today, I may actually have to include the fix you found for your own library!


Mar 2, 2007 at 9:02 AM // reply »
95 Comments

Yup, this a common workaround for almost any web app that contains text with line breaks. Thanks for posting your little code snippet.


Mar 2, 2007 at 9:23 AM // reply »
10,640 Comments

@Thomas,

I like what you have done. I don't quite translate everything the same way. For instance, my CF Query object becomes a simple array of objects; it does not keep the column-first style that CF does. I also don't pass record count and stuff.

But, I do like what you have done. I have some ideas that might help improve it (or maybe not - I am mostly new to AJAX stuff). I would like to clean up what I have and send it to you for review. I will shoot you an email or something later this weekend or next week.


Mar 2, 2007 at 10:08 AM // reply »
33 Comments

@Ben,

I saw the same need as you to have a query as an array instead of a structure, and there's actually an argument that can be passed to make it return it as an array. Not well documented, I admit...

I was about to release a new version, but after reading your post I did a few tests with special characters and ran into one problem when there were double quotes in a string. I just tracked down the problem and found a fix, but I'm a bit puzzled as to why CF is behaving as it is. I'll try to send you an email when I have a sec later to describe the problem, maybe you'll have a clue as to why things are so.


Mar 2, 2007 at 4:30 PM // reply »
2 Comments

Why aren't you using the standard 'jsStringFormat()' function?


Mar 2, 2007 at 5:59 PM // reply »
10,640 Comments

@Ed,

JSStringFormat() just escapes certain characters. JSON is much more complex. It converts entire ColdFusion objects to Javascript, not just strings.


Mar 2, 2007 at 7:52 PM // reply »
33 Comments

Hey Ben, if you downloaded CFJSON earlier today, I recommend that you download the latest version that I just put up. There were some serious bugs that were fixed. And if you have any suggestions I'd love to hear them.


Mar 2, 2007 at 9:01 PM // reply »
2 Comments

"JSStringFormat() just escapes certain characters."

That's exactly what I was referring to. You were getting errors because of carriage returns/line feeds. jsStringFormat() converts those to '\n'. If you use that function on string values, you don't have to roll your own regular expression. Thomas Messier's CFJSON component uses the jsStringFormat() function.


Mar 3, 2007 at 6:33 AM // reply »
9 Comments

This information at last that has returned me on the necessary way :)


Mar 3, 2007 at 9:39 AM // reply »
10,640 Comments

@Ed,

I apologize. You were completely right about JSStringFormat(). I was not familiar with this function and I see now what you are saying. I am going to implement this. Thanks for the tip.


Apr 16, 2007 at 1:19 PM // reply »
1 Comments

Very helpful, even to those of us not using ColdFusion. Thanks! That 'invalid label' solution also saved me a lot of headache earlier. Props.


Apr 16, 2007 at 1:20 PM // reply »
10,640 Comments

Heck yeah! It's all about people helping people :)


Apr 20, 2009 at 12:59 AM // reply »
1 Comments

any idea how to fix 'unterminated string literal' as I try to pass the value of some html tags into javascript function?


Apr 21, 2009 at 9:29 AM // reply »
10,640 Comments

@Brian,

You are not giving us anything to work with.


Aug 3, 2009 at 11:50 PM // reply »
1 Comments

I dont know anything about none of this stuff, but every time I go to tagged or something, it say the same error that everybody is talking about here... Does anybody mind explaining this stuff to me because its beginning to become a true pain the the rectum... lol...


Aug 5, 2009 at 8:49 AM // reply »
10,640 Comments

@Andre,

What do you mean "go to tagged"? What are you doing when you get this error?


Feb 5, 2010 at 9:06 PM // reply »
1 Comments

Sweet, it works. makes total sense.


Feb 17, 2010 at 7:47 PM // reply »
1 Comments

Man, I just wanted you to know that this little tidbit helped me after two hours of banging my head against the monitor, wondering why my ExtJS-provided widget wasn't correctly parsing the JSON that it received from the server...

...and, yes, Firebug *does* rock!


Feb 17, 2010 at 9:07 PM // reply »
10,640 Comments

@Lamont,

Firebug does rock! I can hardly imagine having to go develop without it again.


Feb 26, 2010 at 6:26 PM // reply »
4 Comments

Hi Ben,

Thank you for all your informative blogs.

I have the same issue trying to parse data from a query to json. I have tried everything and no luck.

Is there a place where I can download StringToJSON() udf?

Thanks


Feb 27, 2010 at 11:36 AM // reply »
10,640 Comments

@Mike,

Are you talking about a server-side UDF? What language are you using?


Mar 1, 2010 at 6:34 PM // reply »
4 Comments

Yes, I was talking about the server-side UDF.
I'm using ColdFusion. I figured it out, basically escaping all "funny" characters.

Thanks
Mike
PS I enjoy your blogs...


Mar 1, 2010 at 6:56 PM // reply »
10,640 Comments

@Mike,

You could just use CF8's serializeJSON().


Mar 1, 2010 at 6:58 PM // reply »
4 Comments

True, but this work for CF7 :(


Jo
Mar 23, 2010 at 3:09 PM // reply »
1 Comments

I keep getting the message unterminated string constant when I try to pull up a web site. Would downloading this help? And if so where do I save it to after unzipping?


Mar 23, 2010 at 3:23 PM // reply »
10,640 Comments

@Jo,

No - this only works for a programmer; as a user, you have no control over the error.


May 26, 2011 at 6:23 PM // reply »
2 Comments

Ben, once again, you are the master. I have a script using the jQuery autocomplete plugin and using CF to get query results to return and then populate related form elements. The data being returned in one of the fields had single quotes, line feeds, carriage returns, you name it. I had spent 4 hours with jsStringFormat and trying to write my own jsonStringFormat function. I kept having issues with getting consistent results. Your comment about the serializeJSON in CF8 saved my day. I quickly changed my output with that function and all data is returned clean and well formatted when populated in the textarea.

Thanks again for all your posts. They are appreciated.


Jul 12, 2011 at 6:22 AM // reply »
1 Comments

thanks. i was struggling to see the issue with google maps json strings, but this pointed me in the right direction.



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »