今天开始学习编程里的数据存储啦!
序列化就是把复杂的数据结构变成能存起来或传输出去的形式。在 aardio 里用得最多的是JSON格式,听说这是一种很轻便的数据格式,适合存东西和传数据。
import web.json
import console;
var data = {
name = "张三",
age = 25,
hobbies = {"读书", "跑步"}
}
var jsonStr = web.json.stringify(data,"utf-8")
console.log(jsonStr)
console.pause();
有变身当然就有还原!反序列化就是把JSON字符串变回原来的数据结构,像拆快递一样。在aardio里用 web.json.parse
函数就能实现。
import web.json;
import console;
var jsonStr = '{"person": {"name": "赵六", "age": 35, "contact": {"phone": "13900139000", "email": "zhaoliu@example.com"}}, "projects": [{"name": "项目C", "status": "进行中"}, {"name": "项目D", "status": "已完成"}]}'
var data = web.json.parse(jsonStr)
console.log(data.person.name)
console.log(data.projects[1].name)
console.pause();
学会了变身和还原,接下来就是把数据存到文件里啦!
import web.json
import fsys;
var data = {
title = "学习笔记",
content = "今天学习了数据序列化与存储。"
}
var jsonStr = web.json.stringify(data,"utf-8")
var file = io.file("/note.json", "w+b")
file.write(jsonStr)
file.close()
import web.json;
import console;
var file = io.file("/note.json", "r")
var jsonStr = file.readAll()
file.close()
var data = web.json.parse(jsonStr)
console.log(data.title)
console.log(data.content)
console.pause();
题目是定义学生信息,存到文件再读出来。试着重写了一下代码,发现关键点在于:
stringify
是变身,parse
是还原);我的代码:
import web.json;
import console;
var student = {
name = "小明",
age = 18,
score = 90
}
var jsonStr = web.json.stringify(student,"utf-8")
var file = io.file("student.json", "w+")
file.write(jsonStr)
file.close()
file = io.file("student.json", "r")
jsonStr = file.readAll()
file.close()
var data = web.json.parse(jsonStr)
console.log("姓名:" + data.name)
console.log("成绩:" + tostring(data.score))
console.pause();
io.file
打开文件,write
写入、readAll
读取,记得用完关文件!不过还有点小疑问:
utf-8
编码就没问题,试了下确实可以;总之,今天的学习非常有用,又学到了一个知识点。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。