In JavaScript. How do I convert an object as a string to the object itself?

  • 0
    I have a line "{cat: 5}" , it needs to be converted to an object.
    Note that JSON.parse only parses JSON-like strings. Ie:
    let a = "{cat: 5}"
    console.log(typeof JSON.parse(a)) // SyntaxError
    let b  = '{"cat": 5}'
    console.log(typeof JSON.parse(b)) // object

    Is there a way to implement this without using third party libraries and eval method?
    JavaScript Arya Bass, Oct 23, 2019

  • 3 Answers
  • 0
    const text = "{a:[1,2,{b:3}],c:{d:4},\"e\":\"qqq\"}";

    const json = text.replace(/(?<=[\{,]\s*)([^",\{]*?)(?=\s*:)/g, a=>{
    return '"'+a+'"';
    });

    console.log(text); // {a:[1,2,{b:3}],c:{d:4},"e":"qqq"}
    console.log(json); // {"a":[1,2,{"b":3}],"c":{"d":4},"e":"qqq"}

    const obj = JSON.parse(json);




    Alexander , here is my version, it may also break (if the name of the key should contain a comma or a left curly brace, as well as if one of the values ​​contains something like "{cat: 5}"), but all other options will work with a bang
    Anonymous

  • 0
    Why don't you like eval? You can always generate an empty frame and run eval there so it doesn't interfere with anything.
    Anonymous

  • 0
    the closest thing to reality will be this option:

    var str = "{cat: 5}";
    var items = [];

    var tokens = str.match(/{[^}]+}/g);
    for (var i = 0; i < tokens.length; i++) {
    var segments = tokens[i].split(',');
    var item = {};
    for (var j = 0; j < segments.length; j++) {
    var pair = segments[j].replace(/{|}/, '').split(':');
    item[pair[0].trim()] = pair[1];
    }
    items.push(item);
    }

    var obj = items;
    console.log(obj);


    just sharpen the output later, and you get a great object.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!