How to convert text
"{width: ‘300’}"
to a JSON object in JavaScript?
JSON.parse does not work (Unexpected token w in JSON at position 1).
How to convert text
"{width: ‘300’}"
to a JSON object in JavaScript?
JSON.parse does not work (Unexpected token w in JSON at position 1).
2
Answers
The reason why
JSON.parse()
does not work on this text is that it is not a valid JSON string. However, the text you provided looks like a valid JavaScript object literal, so you can useeval()
or a similar function to convert it to an object. Here is an example:javascript let myText = "{width: '300'}"; let myObject = eval("(" + myText + ")");
In this example, we useeval()
to evaluate the text as JavaScript code and assign the resulting object tomyObject
. However, note that usingeval()
can be dangerous if you don’t trust the source of the code, as it can execute any arbitrary code. In general, it is safer to useJSON.parse()
for parsing JSON strings. If possible, you should try to ensure that your input is valid JSON, and fix any errors or formatting issuesyou have two ways to do this.
1. eval
because your text is in a valid javascript object format, as the other answer said you can use the
eval
function. theeval
function will run the text as javascript code. so consider that anything can run in the eval so you have to trust the text. never useeval
if the text comes from the user.2. regex and replace
if the text is always in a valid javascript object format, you can turn the text into a valid JSON and then parse it. to do this you have to add
"
for the keys and replace'
with"
for the values. you can use this code for these replacements.