簡體   English   中英

如何將 JSON 屬性解析為 Typescript 中的 Map 鍵?

[英]How to parse JSON property as Map key in Typescript?

我想將 JSON 屬性解析為 Map 鍵。 這是 JSON 字符串:

const jsonString = `{
    "DDBProps": {
      "us-east-1": {
        "test": "2",
        "prod": "100"
      },
      "us-west-2": {
        "test": "2",
        "prod": "100"
      }
    },
    "DDBProps2": {
      "us-east-1": {
        "test": "2",
        "prod": "200"
      },
      "us-west-2": {
        "test": "2",
        "prod": "200"
      }
    }
}`

所以,我希望這些“DDBProps”、“DDBProps2”、...“DDBPropsX”是一個 Map 鍵,嵌套值 Map。本質上,類似於Map<string, Map<string, Map<string, string>>> 我想要這個 nest map 結構,因為我需要根據輸入DDBPropsType, region, stage獲取數字(例如這個 JSON 中的“2”、“100”、“200”)。

所以我聲明了接口:

interface ThroughputMap {
    throughputMappings: Map<string,RegionMap>
}

interface RegionMap {
    regionMappings: Map<string, StageMap>
}

interface StageMap {
    stageMappings: Map<string, string>
}

// parse
const ddbScaleMap: ThroughputMap = JSON.parse(ddbScalingMappingsJson);

但是,這不會解析 JSON 以更正結構:

console.log(ddbScaleMap)
// output below
{
    "DDBProps": {
      "us-east-1": {"test": "2","prod": "100"},
      "us-west-2": {"test": "2","prod": "100"}
    },
    "DDBProps2": {
      "us-east-1": {"test": "2","prod": "200"},
      "us-west-2": {"test": "2","prod": "200"}
    }
}


console.log(ddbScaleMap.throughputMappings) // output undefined

我無法將屬性解析為 Map 鍵。

我試過了:

const ddbScaleMap = new Map<string, Map<string, Map<string, string>>>(Object.fromEntries(JSON.parse(jsonString)))

這在嵌套值中沒有正確解析。 意思是, ddbScaleMap.get("DDBProps").get("us-west-2"); 無法調用 .get("us-west-2")。

顯然,有一種方法可以輕松訪問嵌套值而無需轉換為 map。在 TS 中,您可以使用keyof typeof來訪問嵌套值,如下所示:

function getThroughputByKey(key: string, region: string, stage: string): number {
    const defaultThroughputValue = 1;

    const regionToStageMap = ddbScalingMappingsObject[key as keyof typeof ddbScalingMappingsObject];
    const stageToThroughputMap = regionToStageMap[region as keyof typeof regionToStageMap];
    const throughputString = stageToThroughputMap[stage as keyof typeof stageToThroughputMap];
    const throughput = Number(throughputString);

    return throughput || defaultThroughputValue;
}

暫無
暫無

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

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