Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JavaScript object into LITERAL string?

If I have the object literal:

{a: "hello"}

Is there a Javascript function to convert this object into a literal string, so that the output would be the literal syntax:

'{a: "hello"}'

With JSON.stringify the output would be

'{"a": "hello"}'
like image 986
sir-haver Avatar asked Jan 29 '19 19:01

sir-haver


3 Answers

You can do it with JSON.stringify and then with String.replace like follows:

var jsObj =
{
    abc: "hello",
    bca: "allo",
    cab: "dd:cc",
    d: ["hello", "llo", "dd:cc"],
    e: {abc: "hello", bca: "allo", cab: "dd:cc"}
};

function format(obj)
{
    var str = JSON.stringify(obj, 0, 4),
        arr = str.match(/".*?":/g);

    for(var i = 0; i < arr.length; i++)
        str = str.replace(arr[i], arr[i].replace(/"/g,''));

    return str;
}

console.log(format(jsObj));
like image 132
Bharata Avatar answered Oct 16 '22 12:10

Bharata


JavaScript has no built-in functions that will convert an object to a string representation of it which either:

  • Uses identifiers instead of strings for property names
  • Represents the original syntax used to create the object

You could write your own function for the former (at least when the property name can be represented as a literal) but the latter is impossible as JavaScript stores no information about the source code used to create the object in the first place.

like image 27
Quentin Avatar answered Oct 16 '22 14:10

Quentin


Ok just for fun...roll your own?

const stringify = (obj) => {
    // Iterate over keys, reducing to a string
    let str = Object.keys(obj).reduce((acc, cur) => {
        let next = `${cur}: "${obj[cur]}"`;
        return acc
            ? `${acc}, ${next}`
            : `{${next}`;
    }, '');
    
    // Return, appending final '}'
    return `${str}}`;
}

document.write(stringify({
    foo:1,
    bar:'seat'
}));

That said, your exact requirements aren't clear so I'm not sure this will meet them. But it might be a starting point if there's no native solution that works.

like image 37
Madbreaks Avatar answered Oct 16 '22 14:10

Madbreaks