How can I parse a JSON string that has embedded Javascript constants or variables?
For example, how to parse a JSON string like this one?
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": Handlers.NEW
},
{
"value": "Open",
"onclick": Handlers.OPEN
},
{
"value": "Custom",
"onclick": "function(){doSomething(Handlers.OPEN);}"
}
]
}
}
}
All validators of course consider the JSON to be invalid, yet it is perfectly valid when evaluated in a context where the corresponding Javascript objects are defined.
The first thing that comes to mind is to pre-process the string before feeding it to the JSON parser, but that is tricky, since the same strings can occur inside existing strings (as shown in the sample JSON), and it would require some regex fiddling in order to reliably detect whether e.g. Handlers.NEW is used as an undecorated value, or inside an existing string value.
Is there a clean way to handle this use case without having to do manual regex replacements?