JSON to ABAP data structure program
On my current project, I had to write some ABAP code to convert a (deep) ABAP structure to JSON. I have seen at least two projects out there that do the same thing, but nothing that converts JSON to ABAP. So I set out to produce an ABAP program to do this.
UPDATE: You probably want to rather check out this more recent article: Yet another ABAP JSON parser – and some other stuff. SAP has, since this article, also provided a more sophisticated JSON <-> ABAP utility class, /UI2/CL_JSON.
What I present here is a working solution in the form of an ABAP subroutine (which could easily just be put into a class method) that takes a JSON string and any ABAP data structure as a changing parameter, then changes the ABAP data structure so that it is filled with the data from the JSON string.
The subroutine represents a very basic and trusting JSON parser, in that it believes the caller will not pass in any garbage. As such, there is no real JSON syntax checking, and passing rubbish will result in an incorrectly-filled data structure or, at worst, a short dump. In fact, it is very liberal in the sense that keys can be surrounded with double quotes or not, and so can string values, for that matter. Therefore, there is no strict application of JSON rules, though it should work with any JSON-compliant string.
The code represents a little machine that tries to track the state of a cursor as it moves through the given JSON with a number of switches. It is of course recursive, so that it caters for nested objects and arrays as values inside the JSON string, where arrays are treated as ABAP table entries.
The whole thing consists of 105 lines (excluding blanks and comments) which I think is not bad considering it’s ABAP, though I suspect there is probably room for improvement.
You can find the code for the subroutine here: https://gist.github.com/2282070
Here is a little sample ABAP to test the code, that should work on any Basis system: https://gist.github.com/2282244
Hint: If you run into any difficulty, run your JSON string through JSONLint to make sure it is correct!