skip to Main Content

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


  1. 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 use eval() 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 use eval() to evaluate the text as JavaScript code and assign the resulting object to myObject. However, note that using eval() 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 use JSON.parse() for parsing JSON strings. If possible, you should try to ensure that your input is valid JSON, and fix any errors or formatting issues

    Login or Signup to reply.
  2. you 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. the eval 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 use eval if the text comes from the user.

    const text = "{width: '300'}"
    const object = eval(`(${text})`)
    

    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.

    let text = "{width: '300'}"
    text = text.replace(/([,:{]s*)([^,:"'}]+)(s*[:])/g, '$1"$2"$3').replace(/'/g, '"')
    const object = JSON.parse(text)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search