10

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"}'
Bharata
  • 13,509
  • 6
  • 36
  • 50
sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • 1
    One problem is that once the object exists, it's not possible to know how identifier-like property names were expressed when the object was created (or subsequent properties added). They may or may not have had quotes. – Pointy Jan 29 '19 at 19:38
  • 1
    Unsure what your objective is, but you could (mis)use JSON.stringify()... – Stuart Jan 29 '19 at 19:39
  • Maybe this can help https://stackoverflow.com/a/5612876/3565132 – Haris Bouchlis Jan 29 '19 at 19:40
  • 2
    Just to be clear, though, `{"a":"hello"}` is a legal literal object representation, so I'm not sure why the JSON representation isn't sufficient for your purpose. – Paul Jan 29 '19 at 19:41
  • What do you need this for? If we know your use case, we might be able to suggest a suitable workaround. – Bergi Jan 29 '19 at 19:42
  • Thanks guys my use case is that I can send a mutation query to the server and it only accepts: {a: "hello"} And it does not accept JSON: {"a": "hello"} So I thought that as a work around I should convert my object into a literal string – sir-haver Jan 29 '19 at 19:44
  • 4
    Fixing the server so it supports JSON instead of a non-standard data format would be a better bet. – Quentin Jan 29 '19 at 19:58

4 Answers4

6

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));
Bharata
  • 13,509
  • 6
  • 36
  • 50
  • Thank you Brahata it just took me some time to check the responses but I appreciate your effort and it helped me a lot. In the end I understand that I shouldn't pass JSON objects to the server like that because it's prone to bugs, but I did learn how to make manipulations on string from your and other's answers. Thanks! – sir-haver Jan 30 '19 at 17:15
  • @sir-haver, thank you for your response! You can find on my account site a lot of good answers. And **[here is the list of my answers](https://stackoverflow.com/search?q=user:9801830+[javascript])** especially in JavaScript. – Bharata Jan 30 '19 at 17:41
  • this worked perfectly when sending form fields from React to the backend with Graphql :) – André Lucas Aug 28 '20 at 04:48
3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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.

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • @jonaswilms it could easily be modified to support nested objects and arrays. Since the requirements weren’t complete I provided, as mentioned, a starting point that demonstrates a concept. – Madbreaks Jan 30 '19 at 18:08
0

It does convert it to the literal syntax. You are able to create objects with multiple forms of syntax. Both of the following object declarations are valid:

var a = {a: "a"}
var b = {"b": "b"}

If you want to remove the "" around the key you should be able to match them with the following regex /\"(.*?)\":/g and replace them with something like this:

function reformat(str) {
    var myRegexp = /\"(.*?)\":/g;
    match = myRegexp.exec(str);
    while (match != null) {
        str = str.replace(match[0], match[1] + ":");
        match = myRegexp.exec(str);
    }

    return str;
}

Hope that helps :)

Shimmy568
  • 503
  • 2
  • 8