Find closing curly brace of object literal

40 views
Skip to first unread message

Alan Wells

unread,
Feb 15, 2020, 8:13:05 PM2/15/20
to google-apps-sc...@googlegroups.com
I need a way to find the index position of the closing curly brace of an object literal in a string.

function myTestFnk() {

 
//Some content here


 
var objLiteral = {
    key
:"value"
    innerObject = {
      key:"value"
    }
 
}


 
if (1 === 1) {
   
return true;

 
}

 
//Some More content here
}


I thought, maybe I'd find the start of any object literal first, and then find the index of the first ending curly brace after that.

var startOf_Obj_Literal = stringOf_Function.indexOf("= {") || stringOf_Function.indexOf("={");
var dxOfEndOfObjLiteral = stringOf_Function.indexOf("}",startOf_Obj_Literal);


But if someone has a better idea, please let me know.

And I need to find the ending curly brace with no semi-colon after it.


Alan Wells

unread,
Feb 15, 2020, 8:36:15 PM2/15/20
to Google Apps Script Community
What I need to do, is add a colon to the end of all object literals in the function string if there isn't one.  The Apps Script API is giving me an error that there is an "unexpected token" if I don't add a colon to the end of an object literal, when there is no \n newline character after the curly brace.

I can't add a semicolon to every ending curly brace without a semicolon, because that will also generate an error in some situations.

I wonder if there is a way to evaluate the function string somehow and have JavaScript somehow process it to the valid format?

J R Spikeston

unread,
Feb 15, 2020, 8:39:40 PM2/15/20
to google-apps-sc...@googlegroups.com
This sounds like a job for regex. However, I’m not convinced that the error you’re seeing is really being caused by that. It sounds like malformed JSON which can be the result when you’re getting back HTML instead of actual JSON.

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/62f7ba70-4983-461d-828c-9a945cc425a0%40googlegroups.com.

Alan Wells

unread,
Feb 18, 2020, 10:21:24 AM2/18/20
to Google Apps Script Community
I found the following Stack Overflow post, which I used with some minor modifications to get what I needed.

To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-community+unsub...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages