• Dear Cerberus X User!

    As we prepare to transition the forum ownership from Mike to Phil (TripleHead GmbH), we need your explicit consent to transfer your user data in accordance with our amended Terms and Rules in order to be compliant with data protection laws.

    Important: If you accept the amended Terms and Rules, you agree to the transfer of your user data to the future forum owner!

    Please read the new Terms and Rules below, check the box to agree, and click "Accept" to continue enjoying your Cerberus X Forum experience. The deadline for consent is April 5, 2024.

    Do not accept the amended Terms and Rules if you do not wish your personal data to be transferred to the future forum owner!

    Accepting ensures:

    - Continued access to your account with a short break for the actual transfer.

    - Retention of your data under the same terms.

    Without consent:

    - You don't have further access to your forum user account.

    - Your account and personal data will be deleted after April 5, 2024.

    - Public posts remain, but usernames indicating real identity will be anonymized. If you disagree with a fictitious name you have the option to contact us so we can find a name that is acceptable to you.

    We hope to keep you in our community and see you on the forum soon!

    All the best

    Your Cerberus X Team

How does the brl.json module works?

MikeHart

Administrator
Joined
Jun 19, 2017
Messages
3,597
So far i have always used a 3rd party json module.Works great but then we have the official BRL Json module. Which I am not getting how it works.

Do you know how and maybe can provide an example of reading a file. Maybe a Tiled file, or Spritesheet or something more compilcated?

I consider Json and XML crucial for any language and you need to be able to read and maybe write these formats from code. Any help is appreciated.
 
Sorry, nothing more complex than this simple example :)

test.json file:

[{"type":"SKELETON","x":12,"y":23},{"type":"SPIDER","x":1,"y":78}]

CSX code:

Code:
import brl.json
Import mojo

Function Main()

    Local json:String = LoadString("test.json")
  
    Print json
  
    Local parser:JsonParser = New JsonParser(json)
  
    Local arr:JsonArray = JsonArray (parser.ParseValue())
  
    Print arr.Length
  
    Local object1:JsonObject = JsonObject (arr.GetData()[0])
  
    Print "Type: " + object1.GetString("type")
    Print "x: " + object1.GetInt("x")
    Print "y: " + object1.GetInt("y")
  

End

Output:

[{"type":"SKELETON","x":12,"y":23},{"type":"SPIDER","x":1,"y":78}]
2
Type: SKELETON
x: 12
y: 23
 
Here's another example.
linux.json file
JavaScript:
{
    "_comment": "Linux dependencies",
    "id": "linux_dependencies",
    "LinuxMint": {
        "releases": [{
                "release": "18.1",
                "packages": "build-essential cmake libsndfile1-dev libfftw3-dev libvorbis-dev libogg-dev libmp3lame-dev libasound2-dev libjack-jackd2-dev libsamplerate0-dev libsdl-dev libstk0-dev stk libfluidsynth-dev portaudio19-dev libfltk1.3-dev wine-dev libxinerama-dev libxft-dev libgig-dev git qtbase5-dev qttools5-dev-tools qttools5-dev",
                "cmd": "sudo apt-get install",
                "links": "libstdc++.so libopenal1.so",
                "major": 18,
                "minor": 1
            },
            {
                "release": "18",
                "packages": "libgtk+2.0-dev",
                "cmd": "apt-get install",
                "links": "libgtk.so",
                "major": 18,
                "minor": 0
            },
            {
                "release": "17",
                "packages": "todo",
                "cmd": "haven't a clue",
                "links": "who cares",
                "major": 17,
                "minor": 0
            }
        ],
        "compiler_opt": {
            "g++": "-m32",
            "transcc": "-target=GLFW"
        }
    },
    "Ubuntu": {
        "releases": [{
                "release": "16.04",
                "packages": "You must be serious",
                "cmd": "why bother",
                "links": "are in chains",
                "major": 16,
                "minor": 4
            },
            {
                "release": "16.10",
                "packages": "just format the drive",
                "cmd": "You are my slave",
                "links": "sausages",
                "major": 16,
                "minor": 10
            }
        ],
        "compiler_opt": {
            "g++": "-m64",
            "transcc": "-target=Android"
        }
    }
}

And now the Cerberus code
Code:
Strict

Import brl.json
Import mojo.app

Function Main:Int()
    Local list:= New List<CDistroInfo>()
    list.AddLast(GetDistroData("LinuxMint", "18"))
    list.AddLast(GetDistroData("LinuxMint", "18.1"))
    list.AddLast(GetDistroData("LinuxMint", "17"))
    list.AddLast(GetDistroData("Ubuntu", "16.04"))
    list.AddLast(GetDistroData("Ubuntu", "16.10"))
 
    For Local i:= EachIn list
        Details(i)
        Print ""
    Next
    Return 0
End Function

Function Details:Void(linux:CDistroInfo)
    Print "Distribution: " + linux.Distribution
    Print "Json id for location was: " + linux.ReleaseVersion
    Print "Json command line to execute: " + linux.ComandLine
    Print "Json package list to use: " + linux.Packages
    Print "Json symbolic links to create: " + linux.SymLinks
    Print "Json GCC compiler options to use: " + linux.SystemCompilerOpt
    Print "Json Transcc options to use: " + linux.TransccOpt
    Print "Json Distribution major release id: " + linux.MajorVer
    Print "Json Distribution minor release id: " + linux.MinorVer
End Function

Class CDistroInfo
 
    Field distro:String
    Field releaseVersion:String
    Field packages:String
    Field cmdLine:String
    Field sysmlinks:String
    Field majorVer:Int
    Field minorVer:Int
 
    Field cpp:String
    Field transcc:String
 
    Field jsonValue:StringMap<JsonValue>
 
    Method Distribution:String() Property
        Return Self.distro
    End Method
 
    Method ReleaseVersion:String() Property
        Return Self.releaseVersion
    End Method
 
    Method Packages:String() Property
        Return Self.packages
    End Method
 
    Method ComandLine:String() Property
        Return Self.cmdLine
    End Method
 
    Method SymLinks:String() Property
        Return Self.sysmlinks
    End Method
 
    Method MajorVer:Int() Property
        Return Self.majorVer
    End Method
 
    Method MinorVer:Int() Property
        Return Self.minorVer
    End Method
 
    Method SystemCompilerOpt:String() Property
        Return Self.cpp
    End Method
 
    Method TransccOpt:String() Property
        Return Self.transcc
    End Method
 
    Method New(distro:String, val:StringMap<JsonValue>)
        Self.distro = distro
        Self.releaseVersion = val.Get("release").StringValue()
        Self.packages = val.Get("packages").StringValue()
        Self.cmdLine = val.Get("cmd").StringValue()
        Self.sysmlinks = val.Get("links").StringValue()
        Self.cpp = val.Get("g++").StringValue()
        Self.transcc = val.Get("transcc").StringValue()
        Self.majorVer = val.Get("major").IntValue()
        Self.minorVer = val.Get("minor").IntValue()
    End Method
End Class

Class CJSONLoader
    Field jObject:JsonObject
    Field jDistroObj:JsonObject
    Field jReleaseObj:JsonObject
    Field jCompilerObj:JsonObject
 
    Field jDistributionValues:StringMap<JsonValue>
 
    Method New(jFile:String)
        ' Load the data into a json object. See http://www.json.org/ for details on the format
        Self.jObject = New JsonObject(LoadString(jFile))
    End Method
 
    Method ParseDistroData:Void(distro:String, release:String = "")
     
        Local jParser:JsonParser
        Local jReleaseArray:JsonArray
        Local jCompilerValues:StringMap<JsonValue>
     
        ' Get the distribution object
        Self.jDistroObj = JsonObject(jObject.Get(distro).ToJson())
     
        ' Get compiler options object and convert these into a set of JsonValues for later
        Self.jCompilerObj = JsonObject(jDistroObj.Get("compiler_opt").ToJson())
        jCompilerValues = Self.jCompilerObj.GetData()
     
        ' Process releases data object
        jParser = JsonParser(Self.jDistroObj.Get("releases").ToJson())
        jReleaseArray = JsonArray(jParser.ParseValue())
     
        ' Locate the release we want
        Local i:Int = 0
        While i < jReleaseArray.Length()
            Self.jReleaseObj = JsonObject(jReleaseArray.GetData()[i])
            If Self.jReleaseObj.GetString("release") = release Then Exit
            i += 1
        Wend
     
        ' Now to merge all of this into a set of json values
        Self.jDistributionValues = jReleaseObj.GetData()     
        For Local k:= EachIn jCompilerValues.Keys()
            Self.jDistributionValues.Add(k, jCompilerValues.Get(k))
        Next     
    End Method
 
    ' Get the values
    Method Values:StringMap<JsonValue>() Property
        Return Self.jDistributionValues
    End Method

End Class

Function GetDistroData:CDistroInfo(distro:String, release:String = "")
    Local loader:= New CJSONLoader("linux.json")
    loader.ParseDistroData(distro, release)
    Return New CDistroInfo(distro, loader.Values())
End Function

I will see later about knocking up an applications to create a json data file.
 
Last edited:
As promised an example of writing data to JSON format.
Edit: A small fix to set an array to null if there are no items.
Code:
Strict

Import brl.json

#rem
    Simple convert a class into json example
     If you want to do something more advanced,
     then you would need to create a class to
     convert via reflection, but that would be over kill.
    
     The end json should look structured like so
     Object:
         Object:Players
             Object:Player1
                 value:Float
                 value:Array/Null if not list
                     Object:Item1
                         value:Int
                         value:String
                         Value:bool
                     Object:Item2
                         etc...
                 value:String
             Object:Player2
                 etc...
             Object:Player3
                 etc...
    
     Use a lint tool for JSON to check validation, there should be a few around
#end

Const NO_LIST:Bool = False

' The classes to process
Class CObjectItem
    Field id:Int
    Field name:String
    Field switch:Bool

    Method New(id:Int, name:String, switch:Bool)
        Self.id = id
        Self.name = name
        Self.switch = switch
    End Method
   
End Class

Class CCharacter
    Field name:String
    Field health:Float
    Field items:List<CObjectItem> = New List<CObjectItem>()
    Field carrying:Bool
   
    Method New(name:String, list:Bool = True)
        Self.name = name
        Self.health = Rnd(10)
        Self.carrying = list
    End Method
   
    Method Add:Void(objectItem:CObjectItem)
        If Not carrying Then Return
        Self.items.AddLast(objectItem)
    End Method
End Class

' Function to process the CCharacter class
Function ProcessCharacter:JsonValue(obj:CCharacter)
    ' Contruct a json object
    Local jObjMap:StringMap<JsonValue> = New StringMap<JsonValue>()
    jObjMap.Add("name", New JsonString(obj.name))
    jObjMap.Add("health", New JsonNumber(obj.health))
    If Not obj.items.IsEmpty()
        jObjMap.Add("items", JParser(ProcessObjectItems(obj.items).ToJson()))
    Else
        jObjMap.Add("items", New JsonNull())
    Endif
   
    ' The final result must be an object
    Local jObj:JsonObject = New JsonObject(jObjMap)
    Return JParser(jObj.ToJson())
End Function

' Function to process the object class
Function ProcessObjectItems:JsonArray(list:List<CObjectItem>)
    Local jObjStack:Stack<JsonValue> = New Stack<JsonValue>()
    Local jObjMap:StringMap<JsonValue>
    For Local obj:= Eachin list
        ' Get of the object data into a nameless JsonObject
        jObjMap = New StringMap<JsonValue>()
        jObjMap.Add("id", New JsonNumber(obj.id))
        jObjMap.Add("name", New JsonString(obj.name))
        jObjMap.Add("switch", New JsonBool(obj.switch))
        jObjStack.Push(New JsonObject(jObjMap))
    Next
   
    ' Convert our stack of value into a json array
    Return New JsonArray(jObjStack.ToArray())
End Function

' Function to process a string map of players
Function ProcessPlayers:JsonValue(players:StringMap<CCharacter>)
    Local jObjVal:JsonValue
    Local jObjMap:StringMap<JsonValue> = New StringMap<JsonValue>
   
    ' Add each player
    For Local i:= Eachin players.Keys()
        jObjMap.Add(i, ProcessCharacter(players.Get(i)))
    Next
   
    ' Now wrap it all up with an identifier and make it a valid json string
    jObjVal = JParser(New JsonObject(jObjMap).ToJson())   
    jObjMap.Clear
    jObjMap.Add("players", jObjVal)
   
    Return JParser(New JsonObject(jObjMap).ToJson())
End Function

' Helper function to convert a json string into a json value
Function JParser:JsonValue(json:String)
    Local jParser:JsonParser
    jParser = JsonParser(json)
    Return jParser.ParseValue()
End Function

Function Main:Int()
    Local players:StringMap<CCharacter> = New StringMap<CCharacter>
    players.Add("player1", New CCharacter("Mike"))
    players.Add("player2", New CCharacter("Martin"))
    players.Add("player3", New CCharacter("Jason", NO_LIST))
   
    Local s:Bool, i:Int, j:CCharacter
   
    For i = 0  To 3
        For j = Eachin players.Values()
            If Rnd(20)>10 Then s = True Else s = False   
            j.Add(New CObjectItem(i, "item"+i, s))
        Next
    Next
    Print ProcessPlayers(players).ToJson()
    Return 0
End Function
 
Last edited:
Back
Top Bottom