I am parsing many JSONs and DOMs in PHP. The problem is that the my knowledge about the structure of the JSON/DOM is mixed with code. For example, suppose that I have few sources of first and last names. Each data source can look different and have its own tricks, for example:
[ {"firstname": "FirstName1", "lastname": "LastName1"}, {"firstname": "FirstName2", "lastname": "LastName2"} ]
{ "firstnames": ["FirstName1", "FirstName2"], "lastnames": ["LastName1", "LastName2"] }
{ "firstnames": [ {"firstname": "FirstName1", "id": 1}, {"firstname": "FirstName2", "id": 2} ], "lastnames": [ {"lastname": "LastName2", "id": 2}, {"lastname": "LastName1", "id": 1} ] }
So for each data source I write code that turns the JSON into my objects. If the JSON is very complex then the code also is very complex and it is impossible to see the JSON structure in my code. Looking for bugs is very hard.
I want to solve the problem in declarative way, something like a JSON regex where I can tell "first names are in 'firstnames', second names are in 'secondnames', and they are linked by 'id'".
How can I achieve that? Does JSON have some kind of declarative transformation language (like XSLT/XPath for XML)? Are there any strategies or patterns that can be used to make this JSON → Model transformation more declarative?