Sample code for 30+ languages & platforms
PureBasic

Iterate JSON where Member Names are Data Values

See more JSON Examples

Demonstrates how to parse JSON where member names are not keywords, but instead are data values.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

    json.i = CkJsonObject::ckCreate()
    If json.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoadFile(json,"qa_data/json/valuesAsNames.json")

    ; Imagine we have JSON such as the following:

    ; {
    ;   "1680": {
    ;     "entity_id": "1680",
    ;     "type_id": "simple",
    ;     "sku": "123"
    ;   },
    ;   "1701": {
    ;     "entity_id": "1701",
    ;     "type_id": "simple",
    ;     "sku": "456"
    ;   }
    ; }
    ; 

    ; This presents a parsing problem because the member names, such as "1680"
    ; are not keywords.  Instead they are data values.  We don't know what they
    ; may be in advance.  

    ; To solve, we iterate over the members, get the name of each, ...
    numMembers.i = CkJsonObject::ckSize(json)
    i.i
    For i = 0 To numMembers - 1

        name.s = CkJsonObject::ckNameAt(json,i)

        Debug name + ":"
        jRecord.i = CkJsonObject::ckObjectAt(json,i)

        Debug "entity_id: " + CkJsonObject::ckStringOf(jRecord,"entity_id")
        Debug "type_id: " + CkJsonObject::ckStringOf(jRecord,"type_id")
        Debug "sku: " + CkJsonObject::ckStringOf(jRecord,"sku")

        CkJsonObject::ckDispose(jRecord)

    Next


    CkJsonObject::ckDispose(json)


    ProcedureReturn
EndProcedure