Search code examples
javascriptjsonstringify

string containing equals "=" and no quotes convert to JSON


Im currently stuck trying to convert a string into JSON in javascript.

the string im getting from the server is:

"{knee=true, centered=true}"

the outcome im looking for is something like this:

{ knee: true, centered: true}

but since the string is using equals and there are missing quotes the JSON.parse isnt working, I dont know how to solve this. any help will be appreciated, thank you!


Solution

  • The best I could do was this ... It returns value of object in strings though it seems to work perfect ! ( Actually this one challenged me so I had to do it ) :-)

    let str = "{knee = true, centered = true}";
    str = str.replaceAll('{', '')
    str = str.replaceAll('}', '')
    str = str.split(",")
    str = Object.assign({}, str);
    let key_value;
    let key;
    let val;
    for (var i = 0; i < Object.keys(str).length; i++) {
    
      key_value = str[i].split("=");
      key = String(key_value[0]);
      val = key_value[1];
      str[i] = val;
      delete Object.assign(str, {[key]: str[i]
      })[i];
    
    }
    
    console.log(str)