Skip to content

Commit

Permalink
Handle escaped double quotes in JSON (#33)
Browse files Browse the repository at this point in the history
* Add test case for escaped double quotes

* Validate syntax in tests

* Produce valid escaped JSON
  • Loading branch information
Mesoptier authored Feb 19, 2021
1 parent a04122a commit cefd898
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ module.exports = function (source) {
return `module.exports = ${value}`
}

return `module.exports = JSON.parse(\`${JSON.stringify(value)}\`)`
// the outer JSON.stringify is parsed by JavaScript
// the inner JSON.stringify is parsed by JSON.parse
return `module.exports = JSON.parse(${JSON.stringify(JSON.stringify(value))})`
}

exports.raw = true
6 changes: 4 additions & 2 deletions test/fixtures/file-big.json
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,8 @@
},
{
"with-single-quotes": "this 'should' also work"
},
{
"with-double-\"quotes\"": "this \"should\" also work"
}
]

]
3 changes: 3 additions & 0 deletions test/loader-big.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@ describe('Loader', () => {

// this will fail when there is an error e.g: `throw new Error...`
expect(source.startsWith('module.exports = JSON.parse')).toEqual(true)

// validate syntax
expect(() => eval(source)).not.toThrow()
})
})

0 comments on commit cefd898

Please sign in to comment.