prevent app freezes when use JSON.parse
Post

prevent app freezes when use JSON.parse

use JSON.parse

  • Parse json to an object or value.
  • but, Sometimes value to pars is not json.
  • so, JSON.parse code causes error
  • Use try catch to prevent apps from stopping at that time.

example

const parseJSON = (str) => {
    try {
        return JSON.parse(str);
    } catch {
        console.error("str is not JSON::", str);
        return ''; //return empty string;
    }
}

Reference