如何在 JSON 中制作字典的字典?

How to make a dictionary of dictionaries in JSON?

现在我在 JSON

中有这个结构
"Types":[  
            {  
               "LowCadence":[  
                  {  
                     "Reinforcement":"-1",
                     "Weight":"100",
                     "Message":"Pay attention. You're running low cadence. Your cadence is %d steps per minute."
                  }
               ]
            },
            {  
               "NormalCadence":[  
                  {  
                     "Reinforcement":"0",
                     "Weight":"100",
                     "Message":"Great, your cadence is on target. Cadence is %d steps per minute.",
                     "EnforcementSound":"ding"
                  }
               ]
            },
            {  
               "HighCadence":[  
                  {  
                     "Reinforcement":"1",
                     "Weight":"100",
                     "Message":"Slow down. You're running over your planned cadence. Cadence is %d steps per minute."
                  }
               ]
            }
         ]

但我希望它有这样的结构

有谁知道JSON怎么写?

您在 json 中没有 "dictionaries",但是您有 key/value 个数组,它们的工作方式与它们非常相似。

如果您想访问,请在您的代码中:

正常节奏 > 消息你只需要做:

Types["NormalCadence"]["Message"] 

类似于 .Net 词典,但不完全是词典

我相信你的 JSON 看起来像:

var Types = {
    NormalHR: {
        Reinforcement: 0,
        Weight: 100,
        Message: 'Great! Your heart rate is in the zone.',
        EnforcementSound: 'ding'
    },
    HighHR: {
        Reinforcement: 1,
        Weight: 100,
        Message: 'Slow down. Your heart rate is too high!'
    },
    LowHR: {
        Reinforcement: -1,
        Weight: 100,
        Message: 'Speed up. Low heart rate.'
    }
};

正如@Balder 在他们的回答中所说,您可以使用字典式语法访问,例如:

  • Types['NormalHR']['Reinforcement']

您也可以使用 属性-accessor 语法,例如:

  • Types.NormalHR.Reinforcement

我没有包含每个项目的 "type" 的原因是您可以轻松地推断它来构建您的网格 - 如下所示:

  • typeof Types.NormalHR.Reinforcement(这会return"number"
  • typeof Types.NormalHR.Message(这将return"string"

同样,要获得计数 - 您可以计算特定对象的属性。在现代浏览器中,尝试:

  • Object.keys(Types.NormalHR).length(这会return2

旧版浏览器请参考其他方法:How to efficiently count the number of keys/properties of an object in JavaScript?

希望对您有所帮助!

在objective C中你可以这样写:

NSDictonary *types = @{
@"NormalHR": @{
    @"Reinforcement": [NSNumber numberWithInt:0],
    @"Weight": [NSNumber numberWithInt:100],
    @"Message": @"Great! Your heart rate is in the zone.",
    @"EnforcementSound": @"ding"
},
@"HighHR": @{
    @"Reinforcement": [NSNumber numberWithInt:1],
    @"Weight": [NSNumber numberWithInt:100],
    @"Message": @"Slow down. Your heart rate is too high!"
},
@"LowHR": @{
    @"Reinforcement": [NSNumber numberWithInt:-1],
    @"Weight": [NSNumber numberWithInt:100],
    @"Message": @"Speed up. Low heart rate."
}

};