我的html文件中包含<script type="application/json"></script>
。我需要在加载html文件之前更改此脚本中的json对象。我该怎么做呢? json对象看起来类似于:
<script type="application/json">
{
"questionOptions": {
"ques_1": {"type" : "YesNoQuestion","questionText": "messages.questions.1"},
"ques_2": {"type" : "YesNoQuestion","questionText": "messages.questions.2"},
"ques_3": {"type" : "YesNoQuestion","questionText": "messages.questions.3"},
"ques_4": {"type" : "YesNoQuestion","questionText": "messages.questions.4"},
"ques_5": {"type" : "YesNoQuestion","questionText": "messages.questions.5"}
},
"questions": [
"ques_1",
"ques_2",
"ques_3",
"ques_4",
"ques_5"
],
"persist": false,
"intl": {
"locales": "en-US",
"messages": {
"questions": {
"1": "<img src='../images/img1.jpg'>",
"2": "<img src='../images/img2.jpg'>",
"3": "<img src='../images/img3.jpg'>",
"4": "<img src='../images/img4.jpg'>",
"5": "<img src='../images/img5.jpg'>"
},
"yes": "Similar",
"no": "Old",
"dragAndDrop": "<br><span class='preq'>Is the object old or similar?</span><br>Starting dragging the button down to see the picture. Drag and drop to your answer.",
"continue": "Click Next to continue",
"next": "Next",
"back": "Back",
"finish": "Finish",
"thankYou": "Thank you for completing this form."
}
}
}
</script>
我需要随机化问题选项,问题和整个[消息] [问题],但是将它们随机化的方式相同,因为它们在给定数组中的索引相互匹配。
非常感谢帮助。
编辑:添加了匹配的引号。
答案 0 :(得分:1)
这里有一些想法:
除非您可以控制首先生成JSON的内容,否则在加载html文件之前,没有任何方法可以随机化。猜测是硬编码的,如图所示。
questionOptions
和messages
是哈希值。他们的按键顺序并不重要,所以我没有看到随机插入和布置按键的方法。
最后,questions
是一个数组 - 这可能是您想要随机化的唯一内容(并且希望基于此数组顺序在UI上进行一些渲染?)
这里有一小段代码可以添加到数组原型中:
Array.prototype.shuffle = function() {
var j, x, i;
for (i = this.length; i; i--) {
j = Math.floor(Math.random() * i);
x = this[i - 1];
this[i - 1] = this[j];
this[j] = x;
}
return this;
}
然后你可以在你想要随机化的任何数组上调用它,例如:
qdata.questions.shuffle(); //assuming you store that JSON in a variable called qdata
答案 1 :(得分:-1)
在文档加载之前如何将JSON脚本块转换为实时数据并修改原始JSON的小示例:
<script type="application/json">{"foo":"bar"}
</script>
<script>
function randomizeData(data) { return { foo: "something else" }; }
var data;
(function() {
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++) {
if (scripts[i].type === "application/json") {
data = JSON.parse(scripts[i].innerText);
// manipulate/randomize your data here
data = randomizeData(data);
// change the JSON source to whatever you like
scripts[i].innerText = JSON.stringify(data);
break;
}
}
})();
document.write("The value of foo: "+data.foo);
</script>
<body>
</body>