ios - 如何在 JSON 中制作字典字典?
<p><p>现在我在 JSON 中有这个结构</p>
<pre><code>"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."
}
]
}
]
</code></pre>
<p>但我希望它有这样的结构</p>
<p> <img src="/image/yyOyD.png" alt="enter image description here"/> </p>
<p>有人知道如何用 JSON 编写吗?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我相信你的 JSON 看起来像:</p>
<pre><code>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.'
}
};
</code></pre>
<p>正如@Balder 在他们的回答中所说,您可以使用字典样式的语法,例如:</p>
<ul>
<li><code>类型['NormalHR']['Reinforcement']</code></li>
</ul>
<p>您还可以使用属性访问器语法,例如:</p>
<ul>
<li><code>Types.NormalHR.Reinforcement</code></li>
</ul>
<p>我没有包括每个项目的“类型”的原因是你可以很容易地推断出它来构建你的网格 - 如下:</p>
<ul>
<li><code>typeof Types.NormalHR.Reinforcement</code>(这将返回 <code>"number"</code>)</li>
<li><code>typeof Types.NormalHR.Message</code>(这将返回 <code>"string"</code>)</li>
</ul>
<p>同样,要获得计数 - 您可以计算特定对象的属性。在现代浏览器中,尝试:</p>
<ul>
<li><code>Object.keys(Types.NormalHR).length</code>(这将返回 <code>2</code>)</li>
</ul>
<p>对于较旧的浏览器,请参阅此处的其他方法:<a href="https://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip" rel="noreferrer noopener nofollow">How to efficiently count the number of keys/properties of an object in JavaScript?</a> </p>
<p>希望这会有所帮助!</p></p>
<p style="font-size: 20px;">关于ios - 如何在 JSON 中制作字典字典?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/30925963/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/30925963/
</a>
</p>
页:
[1]