PWill2 PWill2 - 9 months ago 41
HTML Question

How can I alter an application/json script within an html file before it executes?

I have an html file with a

<script type="application/json"></script>
inside it. I need to alter the json object within this script before the html file loads. How would I go about doing that? The json object looks something similar to this:

<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": [
"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."

I need to randomize the questionOptions, questions, and intl[messages][questions] but randomize them in the same way as they all match up by index in their given array to each other.

Help is much appreciated.

Edit: Added matching quotes.

Answer Source

A few thoughts here:

  1. There isn't really a way to randomize things before the html file loads, unless you have control over what generates the JSON in the first place, which I'm guessing is hardcoded as shown.

  2. questionOptions and messages are hashes. The order of their keys do not matter, so I don't see a point in randomizing how the keys are inserted and laid out.

  3. Finally, questions is an array - this is probably the only thing you want to randomize (and hopefully there is some rendering to be done on the UI based on this array order?)

Here's a small piece of code you can add to the array prototype:

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;

And you can then invoke it on any array you want to randomize, e.g.:

qdata.questions.shuffle(); //assuming you store that JSON in a variable called qdata