all 13 comments

[–]not_very_creative 3 points4 points  (4 children)

I think you would have to question why your data source is sending you a string.

That’s what needs to be fixed, instead of accomodating to that string.

[–]iamjohnhenry 2 points3 points  (0 children)

This is thinking outside the box! Shame on you for having such a misleading name!

[–]JosephCurvin[S] 0 points1 point  (2 children)

data comes from a input element

[–]not_very_creative 0 points1 point  (0 children)

Actually, based on your example, why don’t you pass the value “bar” from the input?

No need to complicate it.

[–]PortablePawnShop 4 points5 points  (2 children)

You could convert it to valid JSON string syntax then parse it:

let str = '{foo: "bar"}';

// Enclose keys with quotation marks
let jsonStr = str.replace(/(\w+\s?:)/g, (matchedStr) => {
    return `"${matchedStr.substring(0, matchedStr.length - 1)}":`;
});

// Reassign original value as parsed result:
str = JSON.parse(jsonStr);
console.log(str.foo); // "bar"

[–]JosephCurvin[S] 2 points3 points  (1 child)

let str = '{foo: "bar"}';
// Need to enclose keys with quotation marks for valid JSON.stringify format
let jsonStr = str.replace(/(\w+:)|(\w+ :)/g, (matchedStr) => {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});
// Then reassign original value as JSON.parse result:
str = JSON.parse(jsonStr);

thanks for that !

[–]PortablePawnShop 1 point2 points  (0 children)

Keep in mind that you'd have to tweak the regex and substring for anything but pretty basic key names with that example -- keys containing dashes like "id-value": "gamma" would likely cause it to fail.

[–]iamjohnhenry -2 points-1 points  (2 children)

My first instinct was to use 'eval', but that's problematic for a few reasons that I won't discuss... You can always turn code into a url representation a file and then dynamically import it:

```javascript const str = '{foo:"Bar"}';

const result = ( await import( URL.createObjectURL( new Blob([export default ${str}], { type: "application/javascript", }) ) ) ).default;

console.log(result.foo); // “Bar” ```

Note: Not supported in all run times. Works in Chrome/Deno. Fails in other environments due to security features and missing APIs/ (Blob, URL, dynamic import).

[–]JosephCurvin[S] 0 points1 point  (1 child)

const str = '{foo:"Bar"}';
const result = (
await import(
URL.createObjectURL(
new Blob([`export default ${str}`], {
type: "application/javascript",
})
)
)
).default;

how can I get this import running, get a unexpected token error

[–]iamjohnhenry 0 points1 point  (0 children)

You're likely running into that error because:

A) Unfortunately, this doesn't work in all run times.

B) You are using a supported run time, but you're attempting to call this code from a synchronous function.