JSON.parse() wont accept valid JSON - javascript

I am trying to parse the following string: {"text":"Hej"}, in JS
This is valid JSON. It's a property on an object. But when I try to parse it, I get the following error:
Why does this happen?

Simple.. your string isn't valid (for JSON): it contains a control character at position 13.
Have a look for yourself: json_str.charCodeAt(13) and compare with http://en.wikipedia.org/wiki/C0_and_C1_control_codes .
Edit: seems like you had a Line Feed = (LF) = \n in there.

Oh I got it now!
It was a line break, as you can see here:
I will replace line breaks with <br />
Thank so much everybody for the help!

For any future members also getting the issue, here's my problem in depth and how to possibly fix it.
I allowed users to write whatever they wanted in a textarea, and that would be via AJAX inserted into my statuses MySQL table, without escaping any characters like \n or others. This is bad practice and may lead to issues like this.
How to fix it then..
Best practice is to escape it PHP. And it couldn't be simpler, just use the built-in PHP function: nl2br. This will replace all linebreaks with <br />. Here's an example:
$str = "Bar bar ba r foo foo foof foo bar
bar bar bar fooo
more foo foofo bar foo bar";
$new_string = nl2br($str);
If you are a little late to the party, and only realizing this issue a little to late, you can do it in JavaScript too! Like so:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
Just remeber to this before parsing JSON or anything like that. As JSON will error.
Hope it helped you, happy developing!!

Related

How to make new line from a xml response string

I get my data from an API, which return XML, I already convert it to json because I use angularjs, the field that I need, store Songs Lyrics and it used this symbol ↵ when ever it should go to new line.
for example :
You shout it loud↵But I can’t hear a word you say↵I’m talking loud, not saying much↵↵I’m criticized but all your bullets ricochet↵You shoot me down, but I get up
example above, is something that I get when I use console.log() but when I show this field to my HTML page, its just string with no ↵ in it. I don't know why it not show in HTML, and if its something to make new line, it's not happening.
I was thinking to replace ↵ with <br /> is it possible? I will be appreciate it if you guys can help me with that.
UPDATE :
I use angularjs and fill the model with lyric and show it with {{lyric}} in my html
but as you can see in picture, when I use console.log($scope.lyric) string is formated well, but when I show the same model in HTML, its like this
Simple regexr string replace should take care of it:
var str = 'You shout it loud↵But I can’t hear a word you say↵I’m talking loud, not saying much↵↵I’m criticized but all your bullets ricochet↵You shoot me down, but I get up';
var formatted = str.replace(/↵/ig, "<br/>\n");
console.log(formatted);
document.write(formatted);
The regexr finds everything that matches the character between the / signs and replaces them with a standard newline \n and a HTML breakline tag <br/>.
The i and g flags mean Case Insensitive and Search Global respectively.
Case Insensitive catches the characters even if they are in a different case. Search Global means that if you input a multi line string, then it will replace on all lines and not just on the first.
I just figure it out, I let you know how it works in case of anyone else face with same problem :
when I show lyric like this :
<p>{{lyric}}</p>
it ignored my new lines. but when I use this :
<pre>{{lyrics}}</pre>
it works!

Understanding regex in Javascript .replace()

I shouldn't say I actually have a "problem" (the code seems to... work? Although one time it through an error in the console possibly due to environmental reasons), but I'm picking apart a piece of code and I see this:
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
"key" is passed into the function containing this line. As you might expect, it's a string that's ultimately used as the needle in a haystack.
It's sanitizing something, but I can't figure out what it's sanitizing (primarily because I don't have any fluency in regex I guess). JSLint is barking about something also (Unexpected ']') but I think it's a false positive because it's not parsing the regex.
Wasn't sure to ask this at Stack Overflow or at Code Review, but it's not really "review" so here it is.
Any insight from you regexy type people would be much appreciated.
If I got it right it replaces [ with \[ and ] with \], so basically an escaping of square brackets.
These all do the same thing (globally)
var key = 'a[b] [c] [][]d'.replace(/[\[]/g,"\\\[").replace(/[\]]/g,"\\\]");
print(key);
var key = 'a[b] [c] [][]d'.replace(/[\[]/g,'\\[').replace(/[\]]/g,'\\]');
print(key);
var key = 'a[b] [c] [][]d'.replace(/([\[\]])/g,"\\$1");
print(key);

Grabbing the third fragment between square brackets

Still completely stuck with regex's and square brackets. Hopefully someone can help me out.
Say I have a string like this:
room_request[1][1][2011-08-21]
How would I grab the third fragment out of it?
I tried the following, but I'm not exactly sure what I'm doing so it's fairly hard to figure out where I'm going wrong.
.match(/\[(.*?)\]/);
But this returns the [1] fragment. (The first one, I guess).
So then, I asked here on SO and people told me to add a global flag:
.match(/\[(.*?)\]/g)[2];
In other cases that I've used this regex, this worked fine. However, in this case, I want the stuff INSIDE the square brackets. It returns:
[2011-08-21]
But I really want 2011-08-21.
How can I do this? Thanks a lot.
If anyone could recommend any decent resources about regular expressions, that'd be great aswell. I'm starting to understand the very basics but most of this stuff is far too confusing atm. Thanks.
Two possible methods. To grab the third bracketed expression:
.match(/\[.*?\]\[.*?\]\[(.*?)\]/);
Or, if you know that the expression you want is always at the end of the string:
.match(/\[(.*?)\]$/);
var str = "room_request[1][1][2011-08-21]"
var val = str.match(/\[[^\]]*\]\[[^\]]*\]\[([^\]]*)\]/);
alert(val[1]);
This is a little less messy I think:
var r = "room_request[1][1][2011-08-21]";
var match = r.match(/(?:\[([^\]]+)\]){3}/);
console.log(match[1]);
Basically, it picks out the third match of the square brackets containing something. You get the match result back with two matches - the whole [1][1][2011-08-21] (for whatever reason) and the matched date: 2011-08-21
My regex is a little rusty, but this certainly works.

Newline \n problem in JS

I am reading a file with xmlHttp object and splitting the responseText with newlines by split method.
But "\n" character literally doesn't work. It acts like an error in my code and causes my code not even function.
Here is the line:
var lines=myPlaylist.responseText.split("\n");
There is no error if I split the array myPlaylist with other characters.
Just \n causes problem which I fail to understand.
At first, I thought the error was due to white-space:nowrap since I execute my code on Chrome.
Though I never used white-space in anywhere, I tried to set it to normal but it didn't work.
Similarly, I tried my code on other browsers (Firefox, IE etc), it didn't work either. Looks like I have a problem with using \n. Is there any other way to use newline or error with my code?
And by the way, error seems to be a syntax error since it does not just ignore \n character. Simply causes my code not to work
EDIT: An example responseText
[playlist]
File1=http://localhost:7000/Videos/Big%20Buck%20Bunny%20Trailer.ogv
Title1=Bunny Trailer
Length1=23
File2=http://localhost:7000/Videos/Dizzy%20Cat%20Video.ogv
Title2=Kedi
Length2=33
NumberOfEntries=2
Version=2
I found my own solution to my problem.
After using random special characters, \r character used for carriage return worked like a charm for my problem.
It acted like a newline \n character or at least it did its job in my case.
Thanks everyone for answers and helpful comments.
Try using this line
/\n/
Instead of this one
"\n"
Here's an SO thread that will provide a bit more insight
JavaScript string newline character?
EDIT1:
I just tested this and it splits appropriately on new lines. Can you post some of what you're trying to split?
<html>
<script>
function testSplit(value)
{
var lines = value.split(/\n/);
alert(lines);
}
</script>
<body>
<textarea id="test" name="test" onblur="testSplit(this.value);">
</textarea>
</body>
</html>
EDIT2:
Can you try converting your responseText to an object and seeing what you get from it - sorry, just shooting from the hip here since I haven't had time to mock up anything for testing.
eval("var playlistResponse = ("+ myPlaylist.responseText +")");
Here's a somewhat old article that might be useful to you: http://www.peachpit.com/articles/article.aspx?p=443580&seqNum=4
Use \\n instead of \n i tried on my code and it is working fine
This should work without problem.
Are you certain that myPlaylist has a responseText property, and that property is a string?
What happens if you catch an eventual error?
try {
var lines = myPlaylist.responseText.split(/\n/g);
alert(lines.length);
} catch (e) {
alert(e.message);
}

javascript ampersand (&) in return data will not show as value

I have this bit of code:
...
var aData = request.responseXML.getElementsByTagName('data')[0];
var sDescription = aData.getElementsByTagName('description')[0].firstChild.data;
alert(escape(sDescription));
document.getElementById('tempLabourLineDescription').value = sDescription;
...
sDescription is outputting: SUPPORT ASSY-FUEL TANK MOUNTING, R&R (LH) (L-ENG)
I think it is obvious what i want to do here (get the sDescription in to a field called tempLabourLineDescription but that just will not work.
However, if i in my php script replace or delete the &-char from that string it all works fine. So i thought, just escape the darn string. But that will just not work.
alerting the string doesn't work either until i remove the &-character.
What is doing this? Is sDescription not a string when it comes out of the xml file?
How can i solve this?
The answer is in this snippet:
var aData = request.responseXML...
You're expecting XML. An & by itself is not legal XML. You need to output your result like this:
SUPPORT ASSY-FUEL TANK MOUNTING, R&R (LH) (L-ENG)
It's very difficult to tell without seeing your output script, but the first thing to try is to mask the ampersand: &
The neater way, though, would be to add CDATA to your XML output:
<data><![CDATA[SUPPORT ASSY-FUEL TANK MOUNTING, R&R (LH) (L-ENG)]]></data>
your XML parser on client side should understand it no problem.
You escape the ampersand by using the HTML eqv. &
If you are unable to alter the XML output from the server (it's not your app or some other issue), a "hack" fix would be:
function htmlizeAmps(s){
return s.replace(/\x26/g,"&"); //globalreplace "&" (hex 26) with "&"
}
document.getElementById('tempLabourLineDescription').value = htmlizeAmps(sDescription);

Categories

Resources