JSON parse emoji unicode crashing my react native project

Viewed 3919

Whenever I try to display some data fetched in my React Native project from my API endpoint I get this JSON parse error: JSON parse error on line 0 near .."}], [18933, "RC': expected another Unicode escape for the second half of surrogate pair

Clearly, there is a missing escape character for Unicode escape symbol.

My string is "You can try, but I don’t think so "

I tried printing the string in the console and it displays fine, but when I try to display it in React Native's <Text></Text> component my app crashes.

Any guidance would be appreciated.

3 Answers

UPDATE

I found that the problem was with the JavaScript String.substring() method. It does not know how to properly split unicode surrogate pairs and therefore will try to split the string in the middle of a pair if you're unlucky with the positioning.

I solved the problem by using a library called "runes" that properly splits and takes a substring of a string with unicode surrogate pairs honored.

Problem: postComment.substring(0, 35) Solution: runes.substr(postComment, 0, 35)

Simply install the runes library and use runes.substr(yourString, start, end) to handle unicode surrogate pairs in your string :)

Disclaimer: This is more of a guess since I only have your error and the emoji to work with.

The unicode character for 'FACE WITH TEARS OF JOY' is (U+1F602) and the surrogate pair is \uD83D\uDE02.

If you input \uD83D\uDE02 in the text component and that works, then you can convert using

function findSurrogatePair(point) {
  // assumes point > 0xffff
  var offset = point - 0x10000,
      lead = 0xd800 + (offset >> 10),
      trail = 0xdc00 + (offset & 0x3ff);
  return [lead.toString(16), trail.toString(16)];
}

// find pair for U+1F602
findSurrogatePair(0x1f602); // ["d83d", "de02"]

Reference + credit: http://crocodillon.com/blog/parsing-emoji-unicode-in-javascript

Disclaimer: this is more of a guess since I only have your error and the emoji to work with.

Hope this helps!

If your emoji unicode like \uD83D\uDE02 format this javascript function convert unicode to emoji

    var unicodeToChar = function(text) {
  return text.replace(/\\u[\dA-F]{4}/gi, function(match) {
      return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
  });
}
Related