Search code examples
javascriptjsongoogle-apps-scriptgoogle-apps-script-addon

JSON.stringify object with keys without the quotes in subobject


My current object looks like this:

var file_data = ({
            "file_name_as_key":{
                "id":"file_name_as_id",
                "title":"file title",
                "type":"extention type",
                "cat":"category title",
                "cost":"",
                "desc":"Some text that will go here \"Something in quotes\" <strong>Something as bold</strong> some more text.",
                "img":"image url",
                "url":"Coresponding page url ",
                "status":"Updated"
            }
        });

and what I need to have is the following:

var file_data = ({
            "file_name_as_key":{
                id:"file_name_as_id",
                title:"file title",
                type:"extention type",
                cat:"category title",
                cost:0,
                desc:"Some text that will go here \"Something in quotes\" <strong>Something as bold</strong> some more text.",
                img:"image url",
                url:"Coresponding page url ",
                status:"Updated"
            }
        });

I create the object in my Code.gs file then pass the object to the template as JSON.stringify(my_obj).

here is my script:

    var file_data = {};

var i = 0;
fileData.forEach(function (row) {
  i++;
  if(i >= 2){
    file_data[row[8]] = {
        id: row[8],
        title: row[0],
        type: row[1],
        cat: row[2],
        cost: row[3],
        desc: row[4],
        img: row[5],
        url: row[6],
        status: row[7]
    }
  }
});

return JSON.stringify(file_data);

Can anyone suggest how to go about it so that I can get the object in the desired format?

Thanks in advance.


Solution

  • Actually what I needed was easily achievable. All I had to do is to add replace to my return statement in the function

    return JSON.stringify(file_data).replace(/"(\w+)"\s*:/g, '$1:');