egorchik
egorchik

Reputation: 549

JSON parse not parse string (nexpected token D in JSON at position 0)

let str = 'Delete {%{"color":"#fff","content":"1"}%} item from my server';

    const reworkString = (str) => {
      let separators = ['{%', '%}'];
      let newStr = str.split(new RegExp(separators.join('|'), 'g'));

      const objChecker = (el) => {
       JSON.parse(el)
       console.log(el)
       return elm.hasOwnProperty('content');
      }

      newStr = newStr.map(item=>{
        if (objChecker(item)) {
          return 'good'
        }
        else {
          return item
        }
      })


    }

    reworkString(str);

function objChecker is not working I pass to JSON.parse(el) string but I get error Unexpected token D in JSON at position 0 try do json stringify first, but it always return string, not an object, the main idea is I want to do is if its some element from arr, parse it to object

Upvotes: 0

Views: 45

Answers (1)

Laurens
Laurens

Reputation: 2607

Your array also contains strings that are not JSON and cannot be parsed. If you want to skip over these, then make sure to put a try catch around the JSON.parse:

let str = 'Delete {%{"color":"#fff","content":"1"}%} item from my server';

    const reworkString = (str) => {
      let separators = ['{%', '%}'];
      let newStr = str.split(new RegExp(separators.join('|'), 'g'));

      const objChecker = (el) => {
       try {
           JSON.parse(el)
       } catch (e) {
           return false;
       }
       return el.hasOwnProperty('content');
      }

      newStr = newStr.map(item=>{
        if (objChecker(item)) {
          return 'good'
        }
        else {
          return item
        }
      })

    }

    reworkString(str);

Upvotes: 1

Related Questions