簡體   English   中英

從 JSON 解析創建簡單結構

[英]Create Simple Struct from JSON parse

這對我來說很困惑,到目前為止我一直無法找到答案。

我有我的游戲派系列表。 此列表存儲在 .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"] ,而不是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"]等。它可能更具可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM