JSON Parsing and Writing to Database
【Question】
I have a JSON file whose content looks like this:
I need to sort out the individual fields and write them to the database.
There are a number of child and grandchild records under the LIST” field. Our target fields are “GROUPNAME” and “SERVICES”.
“GROUPNAME” values and “SERVICES”’s “SERVICEID” respectively match Groupname values and ID in database table _groups.
Each value of “SERVICES” corresponds to a record in database table Services.
【Answer】
In your case, the JSON strings have multilevel fields and certain fields contain dynamic data, like LIST and SERVICES, under which the node count varies. What’s more, there are attribute names containing a space, like MOVISTAR SPAIN, or a dot, like Requires.Network. These make it difficult to parse in Java or C#. The Structured Process Language (SPL) encapsulates the functionality of parsing JSON and writing result to the database to make the coding rather easy:
A |
B |
C |
|||
1 |
=json(file(“D:/test/json example.json”).read()) |
||||
2 |
=A1.SUCCESS.LIST |
||||
3 |
=create(Groupname,groupid) |
||||
4 |
=create(Serviceid,Servicename,Credit,Time,INFO,Network,Mobile,Provider,PIN,KBH,MEP,PRD,Type,Locks,Reference,groupid) |
||||
5 |
for A2.fno() |
=A2.field(A5) |
|||
6 |
=B5.SERVICES |
||||
7 |
for B6.fno() |
=B6.fname(B7) |
|||
8 |
=B6.field(B7) |
||||
9 |
=A3.record([B5.GROUPNAME,C7]) |
||||
10 |
=A4.record(C8.array()|C7) |
||||
11 |
=connect(“test”) |
||||
12 |
=A11.update(A3,_groups,Groupname,ID:groupid;ID) |
||||
13 |
=A12.update(A4,Services,Serviceid,Servicename,Credit,_Time:Time,INFO,Network,Mobile,Provider,PIN,KBH,MEP,PRD,_Type:Type,_Locks:Locks,_Reference:Reference,groupid;Serviceid) |
A1: Read in the JSON file as a string and import it as a table sequence.
A2: Get records under SUCCESS.LIST.
A3,A4: Generate two new table sequences for database update to commit.
Create fields according to A2’s field count and get field values (child records) from B5, like :![].
Run a loop according to the field count in B5.SERVICES to get field names from C7 and field values from C8. Below is B5.SERVICES:
Now we have gotten the “GROUPNAME” values, the “SERVICEID”s under “SERVICIES” and “SERVICIES” values to populate them into A3 and A4’s table sequences:
Results of database write:
services table:
_group table:
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL