Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The json library
#1
I don't remember if I ever posted something about the json library in the old forum - the one that crashed. But it's very easy to use and can be used for saving and loading most n7 tables. You can read more about the file format here: https://en.wikipedia.org/wiki/JSON

Code:
' json_example.n7
' ---------------
' Using the json library you can turn "any" table into a json string. You can save this string to
' file and load it again to get an exact replica of the original table. So it's a very handy library
' and file format.

include "json.n7"

' Let's say you want to save the player's progress in a game.
data = []
data.lastSaved = time()
data.score = 1349
data.name = "Marcus"
data.level = 5
data.levelScores = [1439, 5131, 1486, 394]
data.position = [x: 10, y: 15]

' Create a file for saving.
f = createfile("savedata.json")
if file(f)
    ' Use JSON_ToString to create a json string and write it to the file.
    write file f, JSON_ToString(data)
    free file f
   
    ' Use JSON_FromFile (there's also JSON_FromString) to load the data into a variable.
    data = JSON_FromFile("savedata.json")
    ' Print out the information loaded from file.
    t = datetime(data.lastSaved)
    pln "lastSaved      = " + t.year + "-" + str(t.month, 2) + "-" + str(t.day, 2) +
            " " + str(t.hour, 2) + ":" + str(t.minute, 2) + ":" + str(t.second)
    pln "score          = " + data.score
    pln "name           = " + data.name
    pln "level          = " + data.level
    pln "levelScores[2] = " + data.levelScores[2]
    pln "position       = " + data.position.x + ", " + data.position.y
else
    pln "Couldn't create file!"
endif

system "pause"

Edit I wrote "most tables". You can assign functions to variabels in an n7 table, and json doesn't support that ofcourse.


Attached Files
.n7   json_example.n7 (Size: 1.39 KB / Downloads: 7)
Reply
#2
(02-01-2024, 04:40 PM)Marcus Wrote: I don't remember if I ever posted something about the json library in the old forum - the one that crashed. But it's very easy to use and can be used for saving and loading most n7 tables. You can read more about the file format here: https://en.wikipedia.org/wiki/JSON
...
Edit I wrote "most tables". You can assign functions to variabels in an n7 table, and json doesn't support that ofcourse.

Thank you for having shared the JSON library. It's remind me of  your post "Platforms and Ladders" https://naalaa.com/forum/thread-25.html where you used JSON to represent each level in the game. It's amazing !

I am going to learn the JSON library now  Big Grin
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)