json - 从 JSON 解析创建简单结构
问题描述
这让我感到困惑,到目前为止我一直无法找到答案。
我有我的游戏的派系列表。此列表存储在 .cdb (CastleDB) 文件中。.cdb 本质上是一种存储 .JSON 的方式,具有像 .csv 这样的行和列样式编辑器的额外好处
此 JSON (.cdb) 文件必须在游戏开始时加载。
这是我的代码:
#Attempt to load from cdb Database.
var data = File.new()
data.open(FactionDB, File.READ)
var content = parse_json(data.get_as_text())
data.close()
“Content”变量是解析后的 JSON,存储为字典,其结构如下:
Sheets
0
name : Factions
columns
0
typeStr : 0
name: FactionName
1
typeStr : 3
name: ReputationValue
lines
0
"FactionName" : Gaea
"ReputationValue" : 4000
1
"FactionName" : Wretched
"ReputationValue" : 0
2
"FactionName" : Naya
"ReputationValue" : 0
3
"FactionName" : Amari
"ReputationValue" : 12000
4
"FactionName" : Proa
"ReputationValue" : 12000
5
"FactionName" : Player
"ReputationValue" : 12000
6
separators
props
customTypes
compress : false
我不确定如何从这本词典中提取所需的信息。优选地,每个 FactionName 和 ReputationValue 对都是一个“Faction”,然后,每个“Faction”都将被添加到一个“Factions”数组中。
我正在尝试构建一个可以在编程/运行时使用的临时结构/字典/列表。
我也不确定当我的程序最终结束时如何重新打包所有这些信息,以便可以保存/覆盖 JSON 中的信息
这是我尝试制作更简单结构的失败尝试:
#for every sheet in the database
#if the sheet name is "Factions"
#then for every column in the Factions sheet
#if the column name is FactionName
#NewEntry is duplicate the Faction
#erase the Factions Name from the faction.
#The Factions Name is the NewEntry
for sheet in content["sheets"]:
if sheet["name"] == "Factions":
for line in sheet["lines"]:
if 'FactionName' in line:
var dictionary = {
Name = line,
Reputation = line
}
FactionArray.push_back(dictionary)
#var new_entry = entry.duplicate()
#new_entry.erase("FactionName")
#FactionData[entry["FactionName"]] = new_entry
解决方案
一方面,GDScript 区分大小写——你需要for sheet in content["Sheets"]
,而不是for sheet in content["sheets"]
.
此外,在这段代码中:
var dictionary = {
Name = line,
Reputation = line
}
您将 Name 和 Reputation 分别设置为整个line
字典。你最终会得到{Name:{FactionName:Gaea, ReputationValue:4000}, Reputation:{FactionName:Gaea, ReputationValue:4000}}
. 你可以添加line
到FactionArray
.
旁注:您可以使用content.Sheets
代替content["Sheets"]
,sheet.name
代替sheet["name"]
等。它可能更具可读性。
推荐阅读
- laravel - 无法在新的 Laravel 项目中加载公共文件 HTTP ERROR 500
- android - 在自定义视图中添加矩形图像
- django - Django ORM查询多个关键字并使用单个查询重新运行多个对象列表
- plsql - 如何获得输出以显示 PL/SQL 游标
- atom-editor - 如何在 Atom 中从 Proto REPL 连接到 nREPL,而无需手动输入主机和端口?
- python - 如何加载 .h5 文件并使用 fastai 进行迁移学习?
- algorithm - 如何计算do while的时间复杂度?
- haskell - Lambda 函数在 Haskell 中的工作原理
- javascript - JS中通过生成器函数的最佳实践
- c - 如何定义一个从用户获取输入并将其存储到程序中进一步使用的变量的函数?