You can create a data structure such as a Parsing Expression Grammar (PEG) that will be used to parse:
string -> object
You can then write a function that iterates through the object's properties and serializes back into a string, or will stringify it:
object -> string
I haven't seen any data structures for defining how stringifying would work (similar to a PEG), but I think this would be possible.
What I'm wondering is if you can create one data structure to do both. That is, define a grammar or something that will allow you to both parse and serialize some text. There would still be two functions (parse and stringify), but they would both take the same data structure / grammar thingy to figure out what to do automatically.
I am asking because I feel like I've read before that the whole original purpose of grammars was for language generation rather than parsing, and parsing only came after. I can imagine a data structure to generate strings, but I'm wondering if it can get more finely tailored so you can give it a data structure (say a parsed URL object), and it would generate the URL string from it without having to write the custom serialization code. The data structure / grammar thing would do the stringification for you. Wondering if that's possible.
Or maybe it's just better to have two data structures. Just trying to think in terms of reducing duplication.