I need to get some data from a JavaScript or TypeScript file into a Chrome Extension I’m building.
I can use a file picker to get the file’s text contents:
const [fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();
However parsing this text isn’t straight forward. This is as far as I've got. Use a regex to find the object, then parse with json5 (https://github.com/json5/json5) which makes the input more flexible:
const regex = /{([\s\S]*?)}/;
const match = str.match(regex);
if(match && match[1]){
return JSON5.parse(match[0]);
}
It feels brittle using a regex in this way. Is there a better solution?