使用 jQuery 将变量解析为 JSON
我正在尝试使用问题列表和单选按钮填充表单。 加载页面时,我有一个变量,其中包含迄今为止的 JSON 格式字符串答案:
var json = '{ "answers" : [{"84" : "Y" },{"85" : "Y" },{"86" : "Y" },{"87" : "Y" },{"88" : "Y" },{"89" : "N" },{"90" : "N" },{"91" : "N" },{"92" : "Y" },{"93" : "N" },{"94" : "Y" },{"95" : "N" },{"96" : "N" },{"97" : "Y" }]}';
我需要循环遍历答案并找到 ID 与数字 IE id="84" 匹配的单选按钮并设置它的值基于相应的值 (Y)。
似乎 getJSON 是我应该查看的内容,但我不需要调用来获取数据,因为我已经拥有了它。
I am trying to populate a form with a list of questions and radio buttons. When the page is loaded I have a variable that contains the answers they have so far as a string in JSON format:
var json = '{ "answers" : [{"84" : "Y" },{"85" : "Y" },{"86" : "Y" },{"87" : "Y" },{"88" : "Y" },{"89" : "N" },{"90" : "N" },{"91" : "N" },{"92" : "Y" },{"93" : "N" },{"94" : "Y" },{"95" : "N" },{"96" : "N" },{"97" : "Y" }]}';
I need to loop through the answers and find the radio button with the ID matching the number IE id="84" and set it's value based on the corresponding value (Y).
seems like getJSON is what I should be looking at but I do not need to make the call to get the data since I already have it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
明白了,删除了上面提到的引号,添加了一个与 ID 匹配的类,这样我就可以选择给定 ID 的所有元素:
我确信可能有一个更优雅的解决方案,但到目前为止效果很好。
Got it, removed the quotes as mentioned above added a class that matched the ID so I could select all elements for a given ID:
I am sure there is probably a more elegant solution but this is working very well so far.
您只需删除外面的引号,它就已经是正确的格式了。
与其他一些格式不同,JSON 基于实际语言,这意味着您可以在常规编码中使用 JSON 格式。 编写 JSON 相当容易。
You could just remove the quotes on the outside and it would already be in the right format.
Unlike some other formats, JSON is based on the actual language, which means that you can use the JSON format in regular coding. It is fairly easy to write JSON.
通常,您只需使用如下所示的每个语句:
Normally you would just use a each statement like below: