首页 > 解决方案 > 从 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

标签: jsondatabasedictionarygodotgdscript

解决方案


一方面,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}}. 你可以添加lineFactionArray.


旁注:您可以使用content.Sheets代替content["Sheets"]sheet.name代替sheet["name"]等。它可能更具可读性。


推荐阅读