JSFiddle - React, Tailwind, and code Playground

by skirtle

JavaScript

// Assumptions:
//
// 1. The format being parsed is JSON-like but using
//    single quotes instead of double quotes.
// 2. Single quotes within strings are escaped using
//    a slash. JSON does not usually allow this.
// 3. The data is 'well-formed'. No validation is
//    being performed to protect against data that
//    isn't in the expected format.
//
// Very little testing has been performed on this
// code. It is screaming out for an extensive set of
// unit tests

function parse (str) {
  let buffer = ''
  
  for (let i = 0; i < str.length; ++i) {
    const ch = str.charAt(i)
    
    if (ch === `'`) {
      buffer += '"'
    } else if (ch === '"') {
      buffer += '\\"'
    } else if (ch === '\\') {
      i++
      const escapedCh = str.charAt(i)
      
      // JSON only allows certain escape sequences
      if ('"\\/bfnrtu'.includes(escapedCh)) {
        buffer += ch + escapedCh
      } else {
        // Oherwise, remove the slash
        buffer += escapedCh
      }
    } else {
      buffer += ch
    } 
  }

  return JSON.parse(buffer)
}

const str = `[{'a': 'hello', 'b': 'special:"\\'chars'}]`

console.log(parse(str))

// eval should give the same output given the assumptions
// but with all the usual risks of using eval
console.log(eval(str))