First, a small bug in your json file. You need a comma after the 40 in line 8.
A json file represents a Type with all its fields and subtypes. Each key in the json file represents a field in the type, and the key's value is the field's value. In your example, you need a type with fields named "property1", "property2", and "array". You also need a type with fields named "element1" and "element2" , and one type with fields "object1" and "object2"
Type element
element1 as String
element2 as String
EndType
Type object
property1 as Integer
property2 as Integer
array as element[]
EndType
Type rock
object1 as object
object2 as object
EndType
crystal as rock
crystal.Load("file.json")
Print(crystal.object2.array[0].element1) //prints "first"
I really don't think this is what you intended. It looks like you intended to have a list of objects which can contain an array of elements. In that case, you can dispense with the "object1/object2" and "element1/element2" and just use json's array notation.
[
{
"property1" : 10,
"property2": 20
},
{
"property1" : 30,
"property2": 40,
"array" : [
{
"element" : "first"
},
{
"element" : "second"
}
]
}
]
Then you can add as many objects and elements that you need, as the code below shows.
// Project: TestJSon
// Created: 2018-05-20
// show all errors
SetErrorMode(2)
// set window properties
SetWindowTitle( "TestJSon" )
SetWindowSize( 1024, 768, 0 )
SetWindowAllowResize( 1 ) // allow the user to resize the window
// set display properties
SetVirtualResolution( 1024, 768 ) // doesn't have to match the window
SetOrientationAllowed( 1, 1, 1, 1 ) // allow both portrait and landscape on mobile devices
SetSyncRate( 30, 0 ) // 30fps instead of 60 to save battery
SetScissor( 0,0,0,0 ) // use the maximum available screen space, no black borders
UseNewDefaultFonts( 1 ) // since version 2.0.22 we can use nicer default fonts
//This type defines a single element
type element
element as string
endtype
//This type will define a single object
type object
property1 as integer
property2 as integer
array as element[]
endtype
//Create an array of objects
objects as object[]
objects.load("test.json")
do
if objects.length >= 0
for i = 0 to objects.length
print ("Object "+str(i))
print("property1 "+str(objects[i].property1))
print("property2 "+str(objects[i].property2))
if Objects[i].array.length >= 0
for j = 0 to objects[i].array.length
print("element "+objects[i].array[j].element)
next j
endif
next i
endif
Sync()
loop