:: krowemoh

Thursday | 26 DEC 2024
Posts Links Other About Now

previous
next

Pure JSON Parsing in BASIC

2023-07-25
basic

I wrote 3 routines that let you query JSON directly from BASIC.

This works for both UniVerse and D3 (which is why it's not an abstraction over UDO.)

It mimics jq style syntax to get elements, objects and arrays.

https://github.com/Krowemoh/TCL-Utilities

JSON.QUERYJSON.PARSEJSON.PARSE.RECURSE

*
    EQU TRUE TO 1
    EQU FALSE TO 0
*
    URL = 'https://dummyjson.com/users/1'
    EXECUTE 'SH -c "curl ' : URL : '"' CAPTURING RAW.TEXT
*
    JSON = ''
*
    CALL JSON.PARSE(RAW.TEXT,JSON)
*
    CALL JSON.QUERY(JSON,'.firstName',FIRST.NAME)
    PRINT 'Name: ' : FIRST.NAME
*
    CALL JSON.QUERY(JSON,'.hair.color',HAIR.COLOR)
    PRINT 'Hair Color: ' : HAIR.COLOR
*
    CALL JSON.QUERY(JSON,'.address.coordinates.lat',LAT)
    PRINT 'Lat: ' : LAT
*
    CALL JSON.QUERY(JSON,'.company.address.coordinates.lat',LAT)
    PRINT 'Company Lat: ' : LAT
*
    STOP
*
* END OF PROGRAM
*
    END
*

which gives you:

Name: Terry
Hair Color: Black
Lat: 38.867033
Company Lat: 36.208114

An example with arrays:

*
    EQU TRUE TO 1
    EQU FALSE TO 0
*
    URL = 'https://dummyjson.com/carts/1'
    EXECUTE 'SH -c "curl ' : URL : '"' CAPTURING RAW.TEXT
*
    JSON = ''
*
    CALL JSON.PARSE(RAW.TEXT,JSON)
*
    CALL JSON.QUERY(JSON,'.products[].id',PRODUCTS)
    CALL JSON.QUERY(JSON,'.products[].title',TITLES)
    CALL JSON.QUERY(JSON,'.products[].price',PRICES)
*
    CARTS.LEN = DCOUNT(PRODUCTS,@AM)
    PRINT 'Number of products: ' : CARTS.LEN
    PRINT
*
    FOR I = 1 TO CARTS.LEN
        PRINT PRODUCTS<I> 'L#5' : TITLES<I> 'L#25' : PRICES<I> 'R#5'
    NEXT I
*
    CALL JSON.QUERY(JSON,'.total',TOTAL)
    PRINT
    PRINT 'Total: ' : TOTAL
*
    STOP
*
* END OF PROGRAM
*
    END
*

which will print:

Number of products: 5

59   Spring and summershoes      20
88   TC Reusable Silicone Magi   29
18   Oil Free Moisturizer 100m   40
95   Wholesale cargo lashing B  930
39   Women Sweaters Wool        600

Total: 2328

I'm pretty happy with how this project turned out.

I posted this to the pick group in google groups: