ARRAY e JSONString
Olá!
Sou novato nessa linguagem e não entendi esta seção do SmallBASIC User Guide:
By ARRAY
Using the command M = ARRAY(JSONString) will create a map variable from the string JSONString.
M = ARRAY("{x:1, y:2, z:3}")
s = "{1:10, 2:5, Name:"SmallBASIC"}" ' The quotation marks of the string SmallBASIC are escaped with " M = ARRAY(s)
A letra variável M pode ter outro identificador, não? E se refere a um array M cujos elementos poderiam ser acessados via M( índice ) ou M[ índice ], por exemplo? Não entendo muito bem, mas se a string é imutável, estática, então como posso usar esse conceito em um exemplo dinâmico? Podem ilustrar com alguns exemplos, por favor. At.te,
Luiz
M is a map variable. As shown in the user guide, you can access the elements of the map variable using either dot-notation or brackets:
M = {1:10, 2:5, Name:"SmallBASIC"}
Print M.1
Print M.2
Print M.Name
' or
Print M[1]
Print M["2"]
Print M["Name"]
See section "Add Key-Value Pairs" to add more elements to the map.
Maybe for your use-case it is better to use an array:
A = []
A << "test"
A << 1
A << sin(0)
print A
print A[0]
print A[1]
print A[2]
Hello,
Thanks for the quick reply! Since JSON strings were not mentioned, I thought it would be better to write a clearer explanation about maps (without discussing nesting for now). Here's an example:
`'creating map by assignment map_name = { key1:1, "key2":1.2, key3:"SmallBASIC" } print "- First map: { key1:1, "key2":1.2, key3:"SmallBASIC" }" print print "printing first map..." print map_name print "printing key1..." print map_name.key1 print map_name("key1") print map_name["key1"] print "printing key2..." print map_name.key2 print map_name("key2") print map_name["key2"] print "printing key3..." print map_name.key3 print map_name("key3") print map_name["key3"] print
'creating map by ARRAY (function?) str_name = "{ key1:2, "key2":2.3, key3:"BigBASIC" }" map_name1 = ARRAY(str_name) print "- Second map: { key1:2, "key2":2.3, key3:"BigBASIC" }" print print "printing second map..." print map_name1 print "printing key1..." print map_name1.key1 print map_name1("key1") print map_name1["key1"] print "printing key2..." print map_name1.key2 print map_name1("key2") print map_name1["key2"] print "printing key3..." print map_name1.key3 print map_name1("key3") print map_name1["key3"] ` Now, my question is: how can I save a map as a JSON file? Should I manually format a string with curly braces, placing the key-value pairs separated by commas? Thanks, Luiz
I'll add some better explanation to the guide.
To save maps to a file as json use TSAVE. See examples for TLOAD for save and load. To convert a map to string (json) use STR. You can then save and load the string with standard file-io.
Olá,
Estou trabalhando em um projeto em SmallBASIC onde preciso armazenar dados em um formato similar ao JSON, mas estou tendo dificuldades em garantir que o arquivo gerado seja adequadamente formatado (com indentação e chaves bem estruturadas). Atualmente, estou usando tload e tsave, mas esses métodos não geram um formato legível de JSON.
O que eu estou tentando fazer: Eu uso tload para carregar um arquivo "json-like" existente, e tsave para gravar os dados de volta, mas isso gera um arquivo com formato simples, sem indentação ou estrutura JSON clara. Eu gostaria de formatar os dados corretamente, como um array de objetos JSON, incluindo chaves e valores, e também garantir a legibilidade do arquivo.
O que já fiz: Criei um arquivo JSON-like manualmente. Carreguei e salvei os dados com tload e tsave, mas o formato não é bem estruturado. Veja o código:
`meu_map = {}
if exist("meu_map.json") then tload "meu_map.json", meu_array else meu_array = [] endif
sub inserir() print "Registrando novo mapa:" meu_map = {} ' ????
repeat input "Chave 1 (inteiro): ", meu_map.key1 until meu_map.key1 > 0
repeat input "Chave 2 (decimal): ", meu_map.key2 until meu_map.key2 > 0.0
repeat input "Chave 3 (texto): ", meu_map.key3 until meu_map.key3 <> ""
meu_array << meu_map print "-------------------------" end sub
sub exibir() print "\nMeu arquivo JSON-like:" tload "meu_map.json", meu_array
for i in meu_array meu_map << array(i) next
print "-------------------------"
for i = 0 to len(meu_array) - 1
print "mapa " + str(i+1) + " chave 1: " + meu_map[i].key1
print "mapa " + str(i+1) + " chave 2: " + meu_map[i].key2
print "mapa " + str(i+1) + " chave 3: " + meu_map[i].key3
print "-------------------------"
next
end sub
INPUT "Quantos registros? ", num_lin for i = 1 to num_lin inserir() next tsave "meu_map.json", meu_array exibir() `
A minha dúvida: Como posso modificar o código para gerar um arquivo mais legível e no formato correto, com indentação, e conseguir carregar os dados de volta corretamente? Devo usar open for output/input para manipulação do arquivo em vez de tload e tsave? Como posso formatar o arquivo com a estrutura JSON correta e ler os dados de volta? Agradeço a ajuda e estou aberto a sugestões!
I think SmallBASIC can't do this kind of formatted json output . I googled a little bit and was surprised that there exist many json formatting tools. You can paste an one-line json string and these tools will convert it to something nicely readable. I'm afraid you need to write this kind of tool for SmallBASIC. I would convert the map using STR to a string and then go character by character through that string and write the character to a file (or new string). Using some if-then, like if(c == ",") then insert new line + spaces. To read the nicely formatted data back, I would tload the file. Every element of the resulting array is a line of the json structure as a string. Take all these strings and concatenate them (using i.e. JOIN).
Olá, por ora resolvi adotar o formato similar a JSON, que chamei anteriormente de "json-like". Ao estudar a sintaxe de SmallBASIC, desenvolvi um script e o publiquei em https://computerlanguagesite.wordpress.com/2025/03/16/smallbasic-tabela-com-units-e-map/. Se puder e quiser, por favor, dê uma olhada e eventuais sugestões. Obrigado!
Thank you for sharing your program. Looks great. I don't have anything to complain. Maybe you can assign the ID automatically. Your program can check for the highest ID used so far, and then increase the ID with every new dataset.