0

I've used JSONP to fetch data from another source which returns a list of words to randomly take one out of which is to be used in a game... my source for this as it stands is;

function processResult(obj) {               
    console.log(obj);
    var blah = JSON.stringify(obj);
    console.log(blah);
}

var jsonp = document.createElement('script');
jsonp.src = 'http://testhangmangame.net76.net?jsonp=processResult';
document.body.appendChild(jsonp);

I was wondering, if and how is it possible to extract one word from that string thanks in advance!


Example of json returned:

{
    "words": [
        "Finitely",
        "Misleading",
        "Dinning",
        "Energizing",
        "Untruest",
        "Menorah",
        "Ghoulish",
        "Realism",
        "Caliphate",
        "Buttercup",
        "Oratorio",
        "Prefix",
        "Gaming",
        "Preshrunk",
        "Harmed",
        "Loop",
        "Banknote",
        "Doily",
        "Rest of words removed"
    ]
}

This json is wrapped in processResult( ... );.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Daniel Morgan
  • 571
  • 1
  • 5
  • 13
  • What does your console output look like? – Chris Cherry Oct 05 '13 at 08:35
  • possible duplicate of [How can I return a random value from an array?](http://stackoverflow.com/questions/3419928/how-can-i-return-a-random-value-from-an-array) – Barmar Oct 05 '13 at 08:35
  • Please post an example of the server response. I believe your question has nothing to do with JSON (JSONP actually doesn't have anything to do with JSON). – Felix Kling Oct 05 '13 at 08:37
  • I've added the json to your question (which you should do yourself in a next question), so that if someone were to come here later, this Q&A can actually be useful to them. – Sumurai8 Oct 05 '13 at 08:45
  • @Sumurai8 thanks for help and the heads up, problem solved now thanks to answer below – Daniel Morgan Oct 05 '13 at 08:50

2 Answers2

4

JSONP takes care of converting the result to an ordinary Javascript object, so JSON is irrelevant. You just need to get the array out of the object and use the standard idiom for selecting a random element.

function processResult(obj) {               
    var words = obj.words;
    var random_word =  words[Math.floor(Math.random() * words.length)];
    console.log("The word is: "+random_word);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Oh brilliant thank you very much! I'll accept your answer as soon as I can. Thank you for the information as well on JSONP – Daniel Morgan Oct 05 '13 at 08:41
0

If the API is well-built and the field in the Json response returns an array:

var arr = json['array_field'];
var random = arr[Math.floor(Math.random() * arr.length)];

If the Json returns a string you'll have to make it an array first:

var arr = json['string_field'].split(/\W{1,}/); // Split by whitespace
var random = arr[Math.floor(Math.random() * arr.length)];
Blaise
  • 13,139
  • 9
  • 69
  • 97